小编典典

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

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


阅读 391

收藏
2020-07-27

共1个答案

小编典典

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);
2020-07-27