gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:42:24 24 4
gpt4 key购买 nike

我有类似以下的内容:

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

最佳答案

Apache HttpClient 对 JSON 一无所知,因此您需要单独构建 JSON。为此,我建议查看简单的 JSON-java图书馆来自 json.org . (如果“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);

关于java - 如何使用 Apache HttpClient 发布 JSON 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12059278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com