How to send a JSON object over HttpClient Request with Android? How to send a JSON object over HttpClient Request with Android? android android

How to send a JSON object over HttpClient Request with Android?


I do this with

httppost.setHeader("Content-type", "application/json");

Also, the new HttpPost() takes the web service URL as argument.


In the try catch loop, I did this:

         HttpPost post = new HttpPost(         "https://www.placeyoururlhere.com");         post.setHeader(HTTP.CONTENT_TYPE,"application/json" );         List<NameValuePair> nameValuePairs = new         ArrayList<NameValuePair>(1);         nameValuePairs.add(new BasicNameValuePair("json", json));         post.setEntity(new UrlEncodedFormEntity(nameValuePairs));         HttpClient client = new DefaultHttpClient();         HttpResponse resp = client.execute(post);         HttpEntity entity = resp.getEntity();         response = EntityUtils.toString(entity);

You can add your nameValurPairs according to how many fields you have.Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.


If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++

If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library. However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/

If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?

If its a REST-API Call like POST or GET to be more specific then its is very simple Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.

Hope this helps.