web-dev-qa-db-fra.com

Java Http Request JSON and Response Handling

J'ai examiné plusieurs autres questions, mais je ne comprends toujours pas tout à fait cela. Je veux POST une chaîne JSON vers une adresse distante, puis récupérer les valeurs de la réponse JSON. J'utilise les bibliothèques Apache pour Java.

public HttpResponse http(String url, String body) throws IOException {

    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity(body);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        //httpClient.execute(request);
        HttpResponse result = httpClient.execute(request);

    } catch (IOException ex) {
    }
    return null;
}

Et en tant que corps, je passerais ce qui suit (un exemple):

{"example":1,"fr":"lol"}

Je n'ai absolument aucune idée de la façon de récupérer les valeurs JSON de la réponse non plus.

14
ThePixelPony

La manière la plus simple consiste à utiliser des bibliothèques comme google-http-Java-client mais si vous voulez analyser la réponse JSON par vous-même, vous pouvez le faire de plusieurs manières, vous pouvez utiliser org.json , json-simple , Gson , minimal-json , jackson-mapper-asl (à partir de 1 .x) ... etc

Un ensemble d'exemples simples:

Utilisation de Gson:

import Java.io.IOException;

import org.Apache.http.HttpResponse;
import org.Apache.http.client.methods.HttpPost;
import org.Apache.http.entity.StringEntity;
import org.Apache.http.impl.client.CloseableHttpClient;
import org.Apache.http.impl.client.HttpClientBuilder;
import org.Apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Utilisation de json-simple:

import Java.io.IOException;

import org.Apache.http.HttpResponse;
import org.Apache.http.client.methods.HttpPost;
import org.Apache.http.entity.StringEntity;
import org.Apache.http.impl.client.CloseableHttpClient;
import org.Apache.http.impl.client.HttpClientBuilder;
import org.Apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

40
vzamanillo