Android中封装Http请求

来源:互联网 发布:鹿晗 知乎 编辑:程序博客网 时间:2024/05/17 23:49


HttpConnectionUtils 支持get post put delete请求 图片请求

 

 

Java代码 复制代码 收藏代码
  1. /** 
  2.  * HTTP connection helper 
  3.  * @author 
  4.  * 
  5.  */  
  6. public class HttpConnectionUtils implements Runnable {  
  7.     private static final String TAG = HttpConnectionUtils.class.getSimpleName();  
  8.     public static final int DID_START = 0;  
  9.     public static final int DID_ERROR = 1;  
  10.     public static final int DID_SUCCEED = 2;  
  11.   
  12.     private static final int GET = 0;  
  13.     private static final int POST = 1;  
  14.     private static final int PUT = 2;  
  15.     private static final int DELETE = 3;  
  16.     private static final int BITMAP = 4;  
  17.   
  18.     private String url;  
  19.     private int method;  
  20.     private Handler handler;  
  21.     private List<NameValuePair> data;  
  22.   
  23.     private HttpClient httpClient;  
  24.   
  25.     public HttpConnectionUtils() {  
  26.         this(new Handler());  
  27.     }  
  28.   
  29.     public HttpConnectionUtils(Handler _handler) {  
  30.         handler = _handler;  
  31.     }  
  32.       
  33.     public void create(int method, String url, List<NameValuePair> data) {  
  34.         Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);  
  35.         this.method = method;  
  36.         this.url = url;  
  37.         this.data = data;  
  38.         ConnectionManager.getInstance().push(this);  
  39.     }  
  40.   
  41.     public void get(String url) {  
  42.         create(GET, url, null);  
  43.     }  
  44.   
  45.     public void post(String url, List<NameValuePair> data) {  
  46.         create(POST, url, data);  
  47.     }  
  48.       
  49.     public void put(String url, List<NameValuePair> data) {  
  50.         create(PUT, url, data);  
  51.     }  
  52.   
  53.     public void delete(String url) {  
  54.         create(DELETE, url, null);  
  55.     }  
  56.   
  57.     public void bitmap(String url) {  
  58.         create(BITMAP, url, null);  
  59.     }  
  60.   
  61.     @Override  
  62.     public void run() {  
  63.         handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));  
  64.         httpClient = new DefaultHttpClient();  
  65.         HttpConnectionParams  
  66.                 .setConnectionTimeout(httpClient.getParams(), 6000);  
  67.         try {  
  68.             HttpResponse response = null;  
  69.             switch (method) {  
  70.             case GET:  
  71.                 response = httpClient.execute(new HttpGet(url));  
  72.                 break;  
  73.             case POST:  
  74.                 HttpPost httpPost = new HttpPost(url);  
  75.                 httpPost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));  
  76.                 response = httpClient.execute(httpPost);  
  77.                 break;  
  78.             case PUT:  
  79.                 HttpPut httpPut = new HttpPut(url);  
  80.                 httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));  
  81.                 response = httpClient.execute(httpPut);  
  82.                 break;  
  83.             case DELETE:  
  84.                 response = httpClient.execute(new HttpDelete(url));  
  85.                 break;  
  86.             case BITMAP:  
  87.                 response = httpClient.execute(new HttpGet(url));  
  88.                 processBitmapEntity(response.getEntity());  
  89.                 break;  
  90.             }  
  91.             if (method < BITMAP)  
  92.                 processEntity(response.getEntity());  
  93.         } catch (Exception e) {  
  94.             handler.sendMessage(Message.obtain(handler,  
  95.                     HttpConnectionUtils.DID_ERROR, e));  
  96.         }  
  97.           ConnectionManager.getInstance().didComplete(this);  
  98.     }  
  99.   
  100.     private void processEntity(HttpEntity entity) throws IllegalStateException,  
  101.             IOException {  
  102.         BufferedReader br = new BufferedReader(new InputStreamReader(entity  
  103.                 .getContent()));  
  104.         String line, result = "";  
  105.         while ((line = br.readLine()) != null)  
  106.             result += line;  
  107.         Message message = Message.obtain(handler, DID_SUCCEED, result);  
  108.         handler.sendMessage(message);  
  109.     }  
  110.   
  111.     private void processBitmapEntity(HttpEntity entity) throws IOException {  
  112.         BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);  
  113.         Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());  
  114.         handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));  
  115.     }  

 

 

ConnectionManager

 

Java代码 复制代码 收藏代码
  1. public class ConnectionManager {  
  2.     public static final int MAX_CONNECTIONS = 5;  
  3.        
  4.     private ArrayList<Runnable> active = new ArrayList<Runnable>();  
  5.     private ArrayList<Runnable> queue = new ArrayList<Runnable>();  
  6.   
  7.     private static ConnectionManager instance;  
  8.   
  9.     public static ConnectionManager getInstance() {  
  10.          if (instance == null)  
  11.               instance = new ConnectionManager();  
  12.          return instance;  
  13.     }  
  14.   
  15.     public void push(Runnable runnable) {  
  16.          queue.add(runnable);  
  17.          if (active.size() < MAX_CONNECTIONS)  
  18.               startNext();  
  19.     }  
  20.   
  21.     private void startNext() {  
  22.          if (!queue.isEmpty()) {  
  23.               Runnable next = queue.get(0);  
  24.               queue.remove(0);  
  25.               active.add(next);  
  26.   
  27.               Thread thread = new Thread(next);  
  28.               thread.start();  
  29.          }  
  30.     }  
  31.   
  32.     public void didComplete(Runnable runnable) {  
  33.          active.remove(runnable);  
  34.          startNext();  
  35.     }  
  36.   
  37. }  

 

 封装的Handler HttpHandler  也可以自己处理

 

Java代码 复制代码 收藏代码
  1. public class HttpHandler extends Handler {  
  2.   
  3.     private Context context;  
  4.     private ProgressDialog progressDialog;  
  5.   
  6.     public HttpHandler(Context context) {  
  7.         this.context = context;  
  8.     }  
  9.   
  10.     protected void start() {  
  11.         progressDialog = ProgressDialog.show(context,  
  12.                 "Please Wait...""processing..."true);  
  13.     }  
  14.   
  15.     protected void succeed(JSONObject jObject) {  
  16.         if(progressDialog!=null && progressDialog.isShowing()){  
  17.             progressDialog.dismiss();  
  18.         }  
  19.     }  
  20.   
  21.     protected void failed(JSONObject jObject) {  
  22.         if(progressDialog!=null && progressDialog.isShowing()){  
  23.             progressDialog.dismiss();  
  24.         }  
  25.     }  
  26.       
  27.     protected void otherHandleMessage(Message message){  
  28.     }  
  29.       
  30.     public void handleMessage(Message message) {  
  31.         switch (message.what) {  
  32.         case HttpConnectionUtils.DID_START: //connection start  
  33.             Log.d(context.getClass().getSimpleName(),  
  34.                     "http connection start...");  
  35.             start();  
  36.             break;  
  37.         case HttpConnectionUtils.DID_SUCCEED: //connection success  
  38.             progressDialog.dismiss();  
  39.             String response = (String) message.obj;  
  40.             Log.d(context.getClass().getSimpleName(), "http connection return."  
  41.                     + response);  
  42.             try {  
  43.                 JSONObject jObject = new JSONObject(response == null ? ""  
  44.                         : response.trim());  
  45.                 if ("true".equals(jObject.getString("success"))) { //operate success  
  46.                     Toast.makeText(context, "operate succeed:"+jObject.getString("msg"),Toast.LENGTH_SHORT).show();  
  47.                     succeed(jObject);  
  48.                 } else {  
  49.                     Toast.makeText(context, "operate fialed:"+jObject.getString("msg"),Toast.LENGTH_LONG).show();  
  50.                     failed(jObject);  
  51.                 }  
  52.             } catch (JSONException e1) {  
  53.                 if(progressDialog!=null && progressDialog.isShowing()){  
  54.                     progressDialog.dismiss();  
  55.                 }  
  56.                 e1.printStackTrace();  
  57.                 Toast.makeText(context, "Response data is not json data",  
  58.                         Toast.LENGTH_LONG).show();  
  59.             }  
  60.             break;  
  61.         case HttpConnectionUtils.DID_ERROR: //connection error  
  62.             if(progressDialog!=null && progressDialog.isShowing()){  
  63.                 progressDialog.dismiss();  
  64.             }  
  65.             Exception e = (Exception) message.obj;  
  66.             e.printStackTrace();  
  67.             Log.e(context.getClass().getSimpleName(), "connection fail."  
  68.                     + e.getMessage());  
  69.             Toast.makeText(context, "connection fail,please check connection!",  
  70.                     Toast.LENGTH_LONG).show();  
  71.             break;  
  72.         }  
  73.         otherHandleMessage(message);  
  74.     }  
  75.   
  76. }  

 

 我这儿server端返回的数据都是json格式。必须包括{success:"true",msg:"xxx",other:xxx} 操作成功success为true.

 

调用的代码:

 

Java代码 复制代码 收藏代码
  1. private Handler handler = new HttpHandler(LoginActivity.this) {       
  2.     @Override  
  3.     protected void succeed(JSONObject jObject) { //自己处理成功后的操作  
  4.         super.succeed(jObject);  
  5.     } //也可以在这重写start() failed()方法  
  6. };  
  7.   
  8. private void login() {  
  9.     ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();  
  10.     params.add(new BasicNameValuePair("email", loginEmail.getText().toString()));  
  11.     params.add(new BasicNameValuePair("password", loginPassword.getText().toString()));  
  12.     String urlString = HttpConnectionUtils.getUrlFromResources(LoginActivity.this, R.string.login_url);  
  13.     new HttpConnectionUtils(handler).post(urlString, params);  
  14.   
  15. }


转自:http://datuo.iteye.com/blog/1094994

0 0
原创粉丝点击