javajsonhttppostapache-commons-httpclient

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


Solution

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