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+?
As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a
StringEntity
.To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:
For Apache HttpClient 4.5 or newer version:
Note:
1 in order to make the code compile, both
httpclient
package andhttpcore
package should be imported.2 try-catch block has been ommitted.
Reference: appache official guide
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
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: