Noe*_*Yap 85 java post json http apache-commons-httpclient
我有以下内容:
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();
Run Code Online (Sandbox Code Playgroud)
它不断回来500.服务提供商说我需要发送JSON.如何使用Apache HttpClient 3.1+完成这项工作?
jan*_*ide 168
Apache HttpClient对JSON一无所知,因此您需要单独构建JSON.为此,我建议从json.org查看简单的JSON-java库.(如果"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);
Run Code Online (Sandbox Code Playgroud)
编辑
注 - 问题中提出的上述答案适用于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);
Run Code Online (Sandbox Code Playgroud)
Zha*_*ang 10
对于Apache HttpClient 4.5或更高版本:
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);
Run Code Online (Sandbox Code Playgroud)
注意:
1为了使代码编译,应该同时导入httpclientpackage和httpcorepackage。
2个try-catch块已被省略。
参考: appache官方指南
Commons HttpClient项目现已停产,并且不再开发。它已被其HttpClient和HttpCore模块中的Apache HttpComponents项目替换。
正如janoside的优秀回答中所述,您需要构造 JSON 字符串并将其设置为StringEntity.
要构造 JSON 字符串,您可以使用任何您熟悉的库或方法。Jackson 库就是一个简单的例子:
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));
Run Code Online (Sandbox Code Playgroud)