Restful web service task : Service « Network « Android






Restful web service task

  

package app.test;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class RestTask extends AsyncTask<HttpUriRequest, Void, String> {

    public static final String HTTP_RESPONSE = "httpResponse";
  
    private Context mContext;
    private HttpClient mClient;
    private String mAction;
  
    public RestTask(Context context, String action) {
        mContext = context;
        mAction = action;
        mClient = new DefaultHttpClient();
    }
  
    public RestTask(Context context, String action, HttpClient client) {
        mContext = context;
        mAction = action;
        mClient = client;
    }
  
    @Override
    protected String doInBackground(HttpUriRequest... params) {
        try{
            HttpUriRequest request = params[0];
            HttpResponse serverResponse = mClient.execute(request);
      
            BasicResponseHandler handler = new BasicResponseHandler();
            String response = handler.handleResponse(serverResponse);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
  
    @Override
    protected void onPostExecute(String result) {
        Intent intent = new Intent(mAction);
        intent.putExtra(HTTP_RESPONSE, result);
        //Broadcast the completion
        mContext.sendBroadcast(intent);
    }

}

   
    
  








Related examples in the same category

1.Map Service
2.Widget Service
3.Search with Restful service
4.Post Restful service
5.Tracker Service
6.Weather web service
7.Access a Web service using GET
8.Alarm service
9.Get Running Services Info
10.Local service demo
11.extends Service
12.Service structure
13.Clock Back Service
14.Voice Recognition Service
15.is Connected by Context.CONNECTIVITY_SERVICE
16.BeatService extends Service and Thread
17.TimeoutService (beta). Here you can register a timeout.
18.Timeout Service
19.Screenshot Service