How receive back JSON data from the server

27 Apr


getJSON(String url)

public static JSONObject getJSONfromURL(String url){

 InputStream is = null;
 String result = "";
 JSONObject jArray = null;

//http post
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost(url);
 HttpResponse response = httpclient.execute(httppost);
 HttpEntity entity = response.getEntity();
 is = entity.getContent();

}catch(Exception e){
 Log.e("log_tag", "Error in http connection "+e.toString());

//convert response to string
 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line + "\n");
 }catch(Exception e){
 Log.e("log_tag", "Error converting result "+e.toString());

//try parse the string to a JSON object
 jArray = new JSONObject(result);
 }catch(JSONException e){
 Log.e("log_tag", "Error parsing data "+e.toString());

return jArray;

The code above can be divided in 3 parts.

  1. the first part makes the HTTP call
  2. the second part converts the stream into a String
  3. the third part converts the string to a JSONObject

Referenced by:

Leave a comment

Posted by on April 27, 2012 in Android, WCF


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: