Friday, December 07, 2012

Retrieve JSON from a REST web service in Android


String result = queryRESTurl("http://location/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, "\n" + nameArray.getString(i) + "\n\n" + "\n" + valArray.getString(i) + "\n");
}   
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:

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...