How to add json to the body of an http post in java

Toran Billups picture Toran Billups · May 14, 2011 · Viewed 34.9k times · Source

I'm trying to post some JSON data in java for an Android app I'm working on. Is the below valid or do I need to push the JSON string in a different way?

HttpPost httpost = new HttpPost("http://test.localhost");
httpost.setEntity(new StringEntity("{\"filters\":true}"));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//... other java code to execute the apache httpclient

Thank you in advance

Answer

laz picture laz · May 14, 2011

You should set the Content-Type header to "application/json". Everything else looks good.