如何使用Apache HttpClient POST 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+是如何完成的呢?
Apache HttpClient不知道任何有关JSON的知识,所以你需要分别构build你的JSON。 为此,我build议从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);