如何使用 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+ 是如何做到的?

原文由 Noel Yap 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 581
2 个回答

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

原文由 janoside 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

2 try-catch 块已被省略。

参考appache官方指南

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

原文由 ZhaoGang 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题