Two Way Communication Via Post with a RESTful Web Service in Android

In order to create an Android app that could consume data from a web services call, I had to be able to post data to the web service.

I posted data via the DefaultHttpClient class, then parsed out the JSON-serialized response.

The code for the post was the following:

public String callServiceAsString (String webservice, ArrayList params) throws Exception {
String response = null;

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(webservice); // the webservice is the url of the resource
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //set parameters to post
ResponseHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler); // execute the post with the Response Handler to return the response
httpclient.getConnectionManager().shutdown(); // tear down the http client
return response;


To parse out the response, I turned the string into a JSON Array:

JSONArray jsonArray = new JSONObject(service.callServiceAsString(webservice)).getJSONArray("result"); // create a JSON Array out of a String
for (int i=0; i < jsonArray.length(); i++){ // iterate through to find the desired values JSONObject childJSONObj = jsonArray.getJSONObject(i); serial = childJSONObj.getString("patron_serial"); name = childJSONObj.getString("patron_name"); }

There you have it, posting data and reading back in data from a RESTful web resource.