I have something like the following:

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

It keeps coming back with a 500. The service provider says I need to send JSON. How is that done with Apache HttpClient 3.1+?

推荐答案

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

一旦生成了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);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

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相关问答推荐

使用SQL查询从SON中查找第n个密钥对值

PostgreSQL 12.17从JSON数组提取元素

JQ-JSON将键转换为对象

属性错误:';ActivitiesClient';对象没有属性';base_url';

需要有关在Ffltter应用程序中解码JSON的帮助;未处理的异常:类型不是类型转换中类型的子类型

规范化JSON数据

使用 jq 获取所有嵌套键和值

go 语言中的 JSON 到 XML

在 PowerShell 中通过 aws cli 创建 cloudwatch alert 时出现字符串解析错误

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

如何在JQ中展平多维数组

如何使用 serde_json 构建有状态的流式解析器?

Golang 解组行为:字段过多?

如何使用 Jackson 定义可选的 json 字段

Golang struct 的 XML 和 JSON 标签?

如何向(JSON)对象的原型添加方法?

在浏览器中查看 JSON 文件

将 json 转换为 C# 数组?

从 JSON 中 Select 不同的值

使用 JSON.NET 序列化/反序列化对象字典