I am an Android Developer

Friday, July 16, 2010

Retrieve JSON from a REST web service

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, "\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:

Post a Comment