如何使用Apache HttpClient发布JSON请求?


89

我有类似以下内容:

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+如何完成?


2
NameValuePair只需添加一个request参数,就不会在代码中发送任何JSON。服务期望接收什么JSON结构,您要发送什么数据?您正在寻找postMethod.setRequestEntity()一个StringRequestEntity包含您的JSON。
菲利普·里查特

Answers:


182

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);

编辑

注意-问题中要求的上述答案适用于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);

如何将json附加到geturl?
楼先生,

1
一直想知道是否parameter可以将a添加到POSTMethod同时设置a RequestEntity?我知道这听起来不合逻辑,但只是好奇。
ASGS

31
对于那些想知道的,StringRequestEntity已被替换StringEntity
2014年

8
在HttpClient的更高版本中,PostMethod已被HttpPost取代。
阿威罗

1
json参考链接已损坏
Simon K.

15

对于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);

注意:

1为了使代码编译,应该同时导入httpclientpackage和httpcorepackage。

2个try-catch块已被省略。

参考appache官方指南

Commons HttpClient项目现已停产,并且不再开发。它已被其HttpClient和HttpCore模块中的Apache HttpComponents项目替换。


2

正如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));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.