Java 从Apache HttpClient中的HttpResponse对象获取JSON属性
我正在使用ApacheHttpClient 4.2,只需要从下面的JSON响应中获取Java 从Apache HttpClient中的HttpResponse对象获取JSON属性,java,json,http,servlets,apache-httpclient-4.x,Java,Json,Http,Servlets,Apache Httpclient 4.x,我正在使用ApacheHttpClient 4.2,只需要从下面的JSON响应中获取title属性 我需要为此使用EntityUtils.toString()方法吗 代码 DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(MAILCHIMP_API_URL); postRequest.setHeader("Content-Type", "application/
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());
{
"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": ""
}
JSON响应
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());
{
"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库):
您可以使用基于ApacheHTTPAPI构建的http请求。文件
private静态最终HttpRequest HTTP\u请求=
HttpRequestBuilder.createPost(MAILCHIMP_API_URL,新类型引用(){
})
.addContentType(ContentType.APPLICATION_JSON)
.addDefaultHeader(“授权”、“基本”+MAILCHIMP\u API\u密钥\u BASE64)
.build();
公开作废法(){
字符串title=HTTP_REQUEST.executeWithBody(json.toString()).get().get(“title”);
}
可能会有帮助。
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");
}