Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST JSON request using Apache HttpClient?

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+?

like image 206
Noel Yap Avatar asked Aug 21 '12 16:08

Noel Yap


People also ask

What is closeable HttpClient?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated. The HttpClient is an interface for this class and other classes. You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder .


1 Answers

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

Once you've generated your JSON, you can use something like the code below to POST it

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); 
like image 143
janoside Avatar answered Sep 30 '22 02:09

janoside