Noel Yap Noel Yap - 1 year ago 195
JSON Question

How to POST JSON request using Apache HttpClient?

I have something like the following:

final String url = "";

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)

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

Answer Source

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 Java library at

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

StringRequestEntity requestEntity = new StringRequestEntity(

PostMethod postMethod = new PostMethod("");

int statusCode = httpClient.executeMethod(postMethod);


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(

HttpPost postMethod = new HttpPost("");

HttpResponse rawResponse = httpclient.execute(postMethod);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download