Handle a Web Service Which is Returning a JSON as Response in Android

Handle a Web Service Which is Returning a JSON as Response in Android

Author: Surender Kumar

Step 1 : Create an Interface


import org.json.JSONObject;

public interface HandleWebServiceResponse {
public void getWebServiceResponse(JSONObject json, int callingId);

}
HandleWebServiceResponse is the interface containing a method getWebServiceResponse.
It contains two parameters:

1. JSON Object i.e Response of web service.
2. Unique Calling ID to identify the response uniquely.

» This interface is to be implemented to the activity that is initializing a web service and is willing to handle
the JSON Response received from the web Service.

Step 2: Calling the web service in the background and sending the response back to the class that have initialized the web service call.


/**
* @author :Surender Kumar
*/


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;

import com.investment.inteface.HandleWebServiceResponse;

/*
This class will call a webservice which is returning a json and will parse it to create a JSON object and the JSON object is
send back to the class which requires this json string.
The web service is called in a separate thread so it doesn't hang your UI while the code is busy in fetching the json result.

*/
public class WebServiceMaster extends AsyncTask {

private Object activity = null;
private int callingId;
private Map parameters = null;
private static String URL = "YOUR_WEBSERVICE_URL";

/*This method will initialize the calling of web service

@param fromActivity
object of the activity that has initialized the webservice i.e the class object which needs the JSON response

@param parameters
the Map object containing the parameters to be send along with the webservice. It contains the key value pair
in the Map object

@param callingId
the unique calling ID of the webservice. This is to identify the webservice response uniquely.
*/



public initWebService(Object fromActivity,Map parameters, int callingId) {
// TODO Auto-generated constructor stub
this.activity = fromActivity;
this.parameters = parameters;
this.callingId = callingId;
this.execute();
}

/*
This is the method of class AsyncTask which is executed in the separated thread. This method is overridden here to execute the particular code in the background so that the main UI does not hangs.
*/

@Override
protected JSONObject doInBackground(Void... arg0) {
// TODO Auto-generated method stub

StringBuilder param = new StringBuilder();
if (parameters != null) {
param.append("?");
for (Object key : parameters.keySet()) {
param.append(key.toString() + "="+ parameters.get(key).toString() + "&");
}
}
String url = URL + param.toString();
Log.i("info", "url :: "+url);
JSONObject json = null;
try {
json = getJSONfromURL(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}



/*

This is the method of class AsyncTask which is executed when the background execution is finished.This method is overriden
here to perform the functionallity when the background thread has finished its work.

HandleWebServiceResponse is the inteface containg a method getWebServiceResponse.

From here we have called the getWebServiceResponse method of the activity that have initialized the call to web service and have implemented the inteface HandleWebServiceResponse.

As a response a JSON Object along with the unique calling id is send back.

*/




@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("log_cat", "calling getWebServiceResponse method");
HandleWebServiceResponse response = (HandleWebServiceResponse) activity;
response.getWebServiceResponse(result, callingId);
super.onPostExecute(result);
}

/*

This is the method to make a http request to the url of web service and parse the json response to
create a json object.

@param url
URL of the webservice to be called.


*/

public static JSONObject getJSONfromURL(String url) throws IOException {

// initialize
InputStream in = null;
String result = "";
JSONObject json = null;

// http get
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();

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

// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
in.close();
} catch (Exception e) {
Log.e("log_cat", "Error converting result " + e.toString());
}

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

}

Step 3: Initializing the webservice from an activity


public class MainActivity extends Activity implements HandleWebServiceResponse{

private static final int WEB_SERVICE_ID_1 = 759176;


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


//Some of your code goes here
}

private void callWebService() {
// TODO Auto-generated method stub

HashMap parameters = new HashMap();
parameters.put("PARAMETER_1_NAME", PARAMETER_1_VALUE);
parameters.put("PARAMETER_1_NAME ", PARAMETER_1_VALUE);
parameters.put("PARAMETER_1_NAME ", PARAMETER_1_VALUE);

WebServiceMaster web_service = new WebServiceMaster(this, parameters,
WEB_SERVICE_ID_1);
}

@Override
public void getWebServiceResponse(JSONObject json, int callingId) {
// TODO Auto-generated method stub

/*
Handle your webservice response here.
You will receive a JSONObject as a response from webservice.

You can easily identify the response uniquely by the unique
Calling ID

*/
}

}

0 comments:

Post a Comment