Thursday, April 30, 2015

Parse GET webservice using GSON library


In this post, We will see steps to parse GET web service.

Step 1 : Create GETservice method . This method will send HTTP get request to server. and we will get HttpResponse in InputStream format.

public String GETService(String url) {
  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(url);

  String line = "";
  try {
   HttpResponse response = httpclient.execute(httpget);

   if (response != null) {
    InputStream inputstream = response.getEntity().getContent();
    line = convertStreamToString(inputstream);
   } else {
    Toast.makeText(mContext, "Unable to complete your request",
      Toast.LENGTH_LONG).show();
   }
  } catch (ClientProtocolException e) {
   Toast.makeText(mContext, "Caught ClientProtocolException",
     Toast.LENGTH_SHORT).show();
  } catch (IOException e) {
   Toast.makeText(mContext, "Caught IOException", Toast.LENGTH_SHORT)
     .show();
  } catch (Exception e) {
   Toast.makeText(mContext, "Caught Exception", Toast.LENGTH_SHORT)
     .show();
  }
  return line;
 }



Step 2 :  Below method will convert input stream format data into String format.

private String convertStreamToString(InputStream is) {
  String line , tempResponse = "" , respoString = "" ;
  
  BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  try {
   while ((line = rd.readLine()) != null)
    tempResponse = tempResponse + line;
   respoString = tempResponse;
   if (TextUtils.isEmpty(respoString))
    return null;
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  Log.d(TAG, "JSON-->" + respoString);
  return respoString.toString();
 }


Step 3:  Once we get data in string format we can use Gson libraries.
This library will help us to convert string json data into java objects .

public ResAndroid resAndroid() {
  String URL = HttpUtils.URL;
  String result = mHttpUtil.GETService(URL);

  if (!TextUtils.isEmpty(result)) {
   return new Gson().fromJson(result, ResAndroid.class);
  }
  return null;
 }
Here ResAndroid is java pojo class having fields same as json response.

We can create Pojo classes from json response using  http://www.jsonschema2pojo.org/ website.


Happy coding !!

No comments:

Post a Comment