Advertisement
Mayur_Pipaliya

getJSONfromURL - Android - JAVA

Jan 25th, 2012
846
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. public static JSONObject getJSONfromURL(String url){
  2.  
  3.     //initialize
  4.     InputStream is = null;
  5.     String result = "";
  6.     JSONObject jArray = null;
  7.  
  8.     //http post
  9.     try{
  10.         HttpClient httpclient = new DefaultHttpClient();
  11.         HttpPost httppost = new HttpPost(url);
  12.         HttpResponse response = httpclient.execute(httppost);
  13.         HttpEntity entity = response.getEntity();
  14.         is = entity.getContent();
  15.  
  16.     }catch(Exception e){
  17.         Log.e("log_tag", "Error in http connection "+e.toString());
  18.     }
  19.  
  20.     //convert response to string
  21.     try{
  22.         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
  23.         StringBuilder sb = new StringBuilder();
  24.         String line = null;
  25.         while ((line = reader.readLine()) != null) {
  26.             sb.append(line + "\n");
  27.         }
  28.         is.close();
  29.         result=sb.toString();
  30.     }catch(Exception e){
  31.         Log.e("log_tag", "Error converting result "+e.toString());
  32.     }
  33.  
  34.     //try parse the string to a JSON object
  35.     try{
  36.             jArray = new JSONObject(result);
  37.     }catch(JSONException e){
  38.         Log.e("log_tag", "Error parsing data "+e.toString());
  39.     }
  40.  
  41.     return jArray;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement