gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:21:36 24 4
gpt4 key购买 nike

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

最佳答案

试试这个(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");

您可能只想创建一个映射器和映射类型的实例。但是,我更愿意创建一个 java 类来表示您的 json 并使用

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

关于java - 从 Apache HttpClient 中的 HttpResponse 对象获取 JSON 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45743357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com