Guest User

Untitled

a guest
Jun 5th, 2012
241
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package utils.serviceloader;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URI;
  6. import java.net.URISyntaxException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.StatusLine;
  13. import org.apache.http.client.ClientProtocolException;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.HttpDelete;
  17. import org.apache.http.client.methods.HttpGet;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.client.methods.HttpPut;
  20. import org.apache.http.client.methods.HttpRequestBase;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import org.apache.http.message.BasicNameValuePair;
  23. import org.apache.http.util.EntityUtils;
  24.  
  25. import ru.recoilme.vkmessages.AndroidApplication;
  26.  
  27. import android.app.IntentService;
  28. import android.content.Intent;
  29. import android.net.Uri;
  30. import android.os.Bundle;
  31. import android.os.ResultReceiver;
  32. import android.util.Log;
  33.  
  34. public class RESTService extends IntentService {
  35.     private static final String TAG = RESTService.class.getName();
  36.    
  37.     public static final int GET    = 0x1;
  38.     public static final int POST   = 0x2;
  39.     public static final int PUT    = 0x3;
  40.     public static final int DELETE = 0x4;
  41.    
  42.     public static final String EXTRA_HTTP_VERB       = "EXTRA_HTTP_VERB";
  43.     public static final String EXTRA_PARAMS          = "EXTRA_PARAMS";
  44.     public static final String EXTRA_RESULT_RECEIVER = "EXTRA_RESULT_RECEIVER";
  45.     public static final String EXTRA_MODE            = "EXTRA_MODE";
  46.     public static final String REST_RESULT           = "REST_RESULT";
  47.  
  48.     public RESTService() {
  49.         super(TAG);
  50.        
  51.     }
  52.    
  53.     @Override
  54.     protected void onHandleIntent(Intent intent) {
  55.         Log.d(TAG, TAG);
  56.         // When an intent is received by this Service, this method
  57.         // is called on a new thread.
  58.        
  59.         Uri    action = intent.getData();
  60.         Bundle extras = intent.getExtras();
  61.        
  62.         if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
  63.             // Extras contain our ResultReceiver and data is our REST action.  
  64.             // So, without these components we can't do anything useful.
  65.             Log.e(TAG, "You did not pass extras or data with the Intent.");
  66.            
  67.             return;
  68.         }
  69.        
  70.         // We default to GET if no verb was specified.
  71.         int            verb     = extras.getInt(EXTRA_HTTP_VERB, GET);
  72.         Bundle         params   = extras.getParcelable(EXTRA_PARAMS);
  73.         ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);
  74.         int            mode     = extras.getInt(EXTRA_MODE,0);
  75.        
  76.         try {            
  77.             // Here we define our base request object which we will
  78.             // send to our REST service via HttpClient.
  79.             HttpRequestBase request = null;
  80.            
  81.             // Let's build our request based on the HTTP verb we were
  82.             // given.
  83.             switch (verb) {
  84.                 case GET: {
  85.                     request = new HttpGet();
  86.                     attachUriWithQuery(request, action, params);
  87.                 }
  88.                 break;
  89.                
  90.                 case DELETE: {
  91.                     request = new HttpDelete();
  92.                     attachUriWithQuery(request, action, params);
  93.                 }
  94.                 break;
  95.                
  96.                 case POST: {
  97.                     request = new HttpPost();
  98.                     request.setURI(new URI(action.toString()));
  99.                    
  100.                     // Attach form entity if necessary. Note: some REST APIs
  101.                     // require you to POST JSON. This is easy to do, simply use
  102.                     // postRequest.setHeader('Content-Type', 'application/json')
  103.                     // and StringEntity instead. Same thing for the PUT case
  104.                     // below.
  105.                     HttpPost postRequest = (HttpPost) request;
  106.                    
  107.                     if (params != null) {
  108.                         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
  109.                         postRequest.setEntity(formEntity);
  110.                     }
  111.                 }
  112.                 break;
  113.                
  114.                 case PUT: {
  115.                     request = new HttpPut();
  116.                     request.setURI(new URI(action.toString()));
  117.                    
  118.                     // Attach form entity if necessary.
  119.                     HttpPut putRequest = (HttpPut) request;
  120.                    
  121.                     if (params != null) {
  122.                         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
  123.                         putRequest.setEntity(formEntity);
  124.                     }
  125.                 }
  126.                 break;
  127.             }
  128.            
  129.             if (request != null) {
  130.                 HttpClient client;
  131.                 Log.e(TAG, "mode"+mode);
  132.                 //if (mode==0) {
  133.                     client = new DefaultHttpClient();
  134.                 //}
  135.                 //else {
  136.                     //client = AndroidApplication.getClient();//new DefaultHttpClient();
  137.                 //}
  138.                 //HttpClient client = AndroidApplication.getClient();//new DefaultHttpClient();
  139.                 //HttpClient client = new DefaultHttpClient();
  140.                
  141.                 // Let's send some useful debug information so we can monitor things
  142.                 // in LogCat.
  143.                 Log.d(TAG, "Executing request: "+ verbToString(verb) +": "+ action.toString());
  144.                
  145.                 // Finally, we send our request using HTTP. This is the synchronous
  146.                 // long operation that we need to run on this thread.
  147.                 HttpResponse response = client.execute(request);
  148.                
  149.                 HttpEntity responseEntity = response.getEntity();
  150.                 StatusLine responseStatus = response.getStatusLine();
  151.                 int        statusCode     = responseStatus != null ? responseStatus.getStatusCode() : 0;
  152.                
  153.                 // Our ResultReceiver allows us to communicate back the results to the caller. This
  154.                 // class has a method named send() that can send back a code and a Bundle
  155.                 // of data. ResultReceiver and IntentService abstract away all the IPC code
  156.                 // we would need to write to normally make this work.
  157.                 if (responseEntity != null) {
  158.                     Bundle resultData = new Bundle();
  159.                     resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
  160.                     resultData.putInt(EXTRA_MODE, mode);
  161.                     receiver.send(statusCode, resultData);
  162.                 }
  163.                 else {
  164.                     receiver.send(statusCode, null);
  165.                 }
  166.             }
  167.         }
  168.         catch (URISyntaxException e) {
  169.             Log.e(TAG, "URI syntax was incorrect. "+ verbToString(verb) +": "+ action.toString(), e);
  170.             receiver.send(0, null);
  171.         }
  172.         catch (UnsupportedEncodingException e) {
  173.             Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
  174.             receiver.send(0, null);
  175.         }
  176.         catch (ClientProtocolException e) {
  177.             Log.e(TAG, "There was a problem when sending the request.", e);
  178.             receiver.send(0, null);
  179.         }
  180.         catch (IOException e) {
  181.             Log.e(TAG, "There was a problem when sending the request.", e);
  182.             receiver.send(0, null);
  183.         }
  184.     }
  185.  
  186.     private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
  187.         try {
  188.             if (params == null) {
  189.                 // No params were given or they have already been
  190.                 // attached to the Uri.
  191.                 request.setURI(new URI(uri.toString()));
  192.             }
  193.             else {
  194.                 Uri.Builder uriBuilder = uri.buildUpon();
  195.                
  196.                 // Loop through our params and append them to the Uri.
  197.                 for (BasicNameValuePair param : paramsToList(params)) {
  198.                     uriBuilder.appendQueryParameter(param.getName(), param.getValue());
  199.                 }
  200.                
  201.                 uri = uriBuilder.build();
  202.                 request.setURI(new URI(uri.toString()));
  203.             }
  204.         }
  205.         catch (URISyntaxException e) {
  206.             Log.e(TAG, "URI syntax was incorrect: "+ uri.toString(), e);
  207.         }
  208.     }
  209.    
  210.     private static String verbToString(int verb) {
  211.         switch (verb) {
  212.             case GET:
  213.                 return "GET";
  214.                
  215.             case POST:
  216.                 return "POST";
  217.                
  218.             case PUT:
  219.                 return "PUT";
  220.                
  221.             case DELETE:
  222.                 return "DELETE";
  223.         }
  224.        
  225.         return "";
  226.     }
  227.    
  228.     private static List<BasicNameValuePair> paramsToList(Bundle params) {
  229.         ArrayList<BasicNameValuePair> formList = new ArrayList<BasicNameValuePair>(params.size());
  230.        
  231.         for (String key : params.keySet()) {
  232.             Object value = params.get(key);
  233.            
  234.             // We can only put Strings in a form entity, so we call the toString()
  235.             // method to enforce. We also probably don't need to check for null here
  236.             // but we do anyway because Bundle.get() can return null.
  237.             if (value != null) formList.add(new BasicNameValuePair(key, value.toString()));
  238.         }
  239.        
  240.         return formList;
  241.     }
  242.  
  243. }
RAW Paste Data