Java HttpRequest JSON &响应处理 [英] Java HttpRequest JSON & Response Handling

查看:23
本文介绍了Java HttpRequest JSON &响应处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了其他几个问题,但我仍然不完全理解这一点.我想将 JSON 字符串 POST 到远程地址,然后从 JSON 响应中检索值.我正在使用 Java 的 Apache 库.

I have looked at several other questions, but I still don't fully understand this. I want to POST a JSON string to a remote address and then retrieve the values from the JSON response. I am using the Apache libraries for 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;
}

作为正文,我将传递以下内容(示例):

And as body, I would pass the following (an example):

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

我也完全不知道如何从响应中检索 JSON 值.

I have absolutely no idea about how to retrieve the JSON values from the response, either.

推荐答案

最简单的方法是使用像 google-http-java-client 但如果你想自己解析 JSON 响应,你可以通过多种方式来做到这一点,你可以使用 org.jsonjson-simpleGsonminimal-jsonjackson-mapper-asl(来自 1.x)...等

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

一组简单的例子:

使用 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;
        }
    }
}

使用 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;
    }
}

等等...

这篇关于Java HttpRequest JSON &响应处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆