Monday, 24 September 2012

Connect to remote mysql db with PHP webservice, and parse the JSON response object returned using JAVA

Hi, here is a sample code on how to connect to a remote mysql db using a php and parse the JSON response object returned


                  HttpClient httpclient = new DefaultHttpClient();

                 Inputstream is;
                 HttpPost httppost = new HttpPost("http://www.hostname.com/files/getbrowsedata.php");
               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,"UTF-8"),8);
               StringBuilder sb = new StringBuilder();
               String line = null;
               while ((line = reader.readLine()) != null) {
                       sb.append(line + "\n");
               }
               System.out.println("sb::" +sb);
                String result=sb.toString();
               is.close();
       

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

//parse the JSON response object
 try{
       
        JSONObject json = new JSONObject(result);
        JSONArray json_array = json.getJSONArray("display");
       
            for (int i = 0; i < json_array.length(); i++) {
                JSONObject result_json_object = json_array.getJSONObject(i);
                String column1= result_json_object.getString("col_name_1");
              String column2= result_json_object.getString("col_name_2");
   
                System.out.println(" column1 ::"+ column2 );
             
                }
            }
        }catch(JSONException e){
             Log.e("log_tag", "Error parsing data "+e.toString());
                
        }


No comments:

Post a Comment

Got to say something?...Leave your comments here