我有以下内容:
final String url = "http://example.com";
final HttpClient httpClient = new HttpClient();
final PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json");
postMethod.addParameters(new NameValuePair[]{
new NameValuePair("name", "value)
});
httpClient.executeMethod(httpMethod);
postMethod.getResponseBodyAsStream();
postMethod.releaseConnection();
它不断回来500.服务提供商说我需要发送JSON。如何使用Apache HttpClient 3.1 +?
完成答案 0 :(得分:158)
Apache HttpClient对JSON一无所知,因此您需要单独构建JSON。为此,我建议您从JSON-java查看简单的json.org库。 (如果“JSON-java”不适合你,json.org有很多不同语言的库。)
生成JSON后,您可以使用类似下面的代码来发布它
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
修改强>
注 - 上述答案,如问题所述,适用于Apache HttpClient 3.1。但是,为了帮助任何人寻找针对最新Apache客户端的实现:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
答案 1 :(得分:6)
对于 Apache HttpClient 4.5 或更高版本:
@babel/polyfill
注意:
1为了编译代码,应同时导入 CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
软件包和httpclient
软件包。
2个try-catch块已被省略。
Commons HttpClient项目现已终止,并且不再存在 正在开发中。它已被Apache HttpComponents取代 HttpClient和HttpCore模块中的项目
答案 2 :(得分:1)
正如 janoside 的优秀答案所述,您需要构建JSON字符串并将其设置为StringEntity
。
要构造JSON字符串,您可以使用您熟悉的任何库或方法。杰克逊图书馆就是一个简单的例子:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));