从Apache HttpClient中的HttpResponse对象获取JSON属性

时间:2017-08-17 19:18:24

标签: java json http servlets apache-httpclient-4.x

我正在使用Apache HttpClient 4.2,只需要从下面的JSON响应中获取title属性。

我需要为此使用EntityUtils.toString()方法吗?

代码

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(MAILCHIMP_API_URL);

postRequest.setHeader("Content-Type", "application/json");
postRequest.setHeader("Authorization", "Basic " + MAILCHIMP_API_KEY_BASE64);

StringEntity entity = new StringEntity(json.toString(), "UTF8");
postRequest.setEntity(entity);

HttpResponse response = httpClient.execute(postRequest);

// Closes the connection
EntityUtils.consume(response.getEntity());

JSON响应

{
  "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
  "title": "Member Exists",
  "status": 400,
  "detail": "user@domain.com is already a list member. Use PUT to insert or update list members.",
  "instance": ""
}

2 个答案:

答案 0 :(得分:1)

试试这个(jackson2 lib):

TypeReference<Map> mapType = new TypeReference<Map>() {};
ObjectMapper mapper = new ObjectMapper();
Map<String, String> responseJson = 
mapper.readValue(response.readEntity(String.class), mapType);
String typeValue = responseJson.get("type");

可能您可能只想创建一个mapper和mapType实例。 但是,我更愿意创建一个代表你的json并使用

的java类
mapper.readValue(response.readEntity(String.class), YourType.class)

答案 1 :(得分:0)

您可以使用基于apache http api构建的http请求。文档here

  private static final HttpRequest<Map<String, Object>> HTTP_REQUEST =
            HttpRequestBuilder.createPost(MAILCHIMP_API_URL, new TypeReference<Map<String, Object>>() {
            })
                    .addContentType(ContentType.APPLICATION_JSON)
                    .addDefaultHeader("Authorization", "Basic " + MAILCHIMP_API_KEY_BASE64)
                    .build();

    public void method() {
        String title = HTTP_REQUEST.executeWithBody(json.toString()).get().get("title");
    }