RSS

How receive back JSON data from the server

27 Apr

By: http://p-xr.com/

getJSON(String url)


public static JSONObject getJSONfromURL(String url){

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

//http post
 try{
 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
 try{
 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");
 }
 is.close();
 result=sb.toString();
 }catch(Exception e){
 Log.e("log_tag", "Error converting result "+e.toString());
 }

//try parse the string to a JSON object
 try{
 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: http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/

Advertisements
 
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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: