我有如下代码:
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+中完成这个任务?
NameValuePair
只是添加了一个请求参数,代码中没有发送任何 JSON。服务端期望接收什么样的 JSON 结构?你要发送的数据是什么?你需要使用postMethod.setRequestEntity()
和包含你的 JSON 的StringRequestEntity
。 - Philipp Reichart