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

我有类似下面的内容:

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+是如何做到这一点的?


答案 1

Apache HttpClient对JSON一无所知,所以你需要单独构建你的JSON。为此,我建议从 json.org 中查看简单的JSON-java库。(如果“JSON-java”不适合你,json.org 有一大堆不同语言的库。

生成 JSON 后,可以使用以下代码进行 POST

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

答案 2

对于 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 为了使代码编译,应该同时导入包和包。httpclienthttpcore

2 已省略 try-catch 块。

参考阿帕切官方指南

Commons HttpClient项目现已结束,不再开发。它已被Apache HttpComponents项目的HttpClient和HttpCore模块所取代。