Saturday, February 11, 2012

How to Retrieve JSON from a REST web service through android code?

Create a JSONObject from the result of a call upon a webservice which provides well formatted JSON response.

String result = queryRESTurl("http://location/of/wellformed/json.json");


try{
JSONObject json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.i(TAG, "<jsonname" + i + ">\\n" + nameArray.getString(i) + "\\n</jsonname" + i + ">\\n" + "<jsonvalue" + i + ">\\n" + valArray.getString(i) + "\\n</jsonvalue" + i + ">");
}
}
catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;

try {
response = httpclient.execute(httpget);
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i(TAG, "Result of converstion: [" + result + "]");

instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}

return null;
}

No comments:

Post a Comment