【问题标题】:Fetch JSON property from HttpResponse object in Apache HttpClient从 Apache HttpClient 中的 HttpResponse 对象获取 JSON 属性
【发布时间】:2018-01-26 08:32:09
【问题描述】:

我使用的是 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": ""
}

【问题讨论】:

  • This 可能会有所帮助。

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


【解决方案1】:

试试这个(jackson2 库):

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 实例。 但是,我更愿意创建一个 java 类来代表你的 json 并使用

mapper.readValue(response.readEntity(String.class), YourType.class)

【讨论】:

    【解决方案2】:

    您可以使用基于 apache http api 构建的 http-request。文档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");
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 2012-12-04
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2022-01-14
      相关资源
      最近更新 更多