Android实战之HttpClient


最近在看Android的开发,其中用到了HttpClient来提交或者获取server端的数据,但是Android自带的API还是有点不好用,所以自己根据自己的需要就做了一个包装,如下:

HttpConnectionUtil类是一个工具类,其中提供了同步和异步方法,并且目前是支持http的Get和Post方法

  1. import java.io.BufferedReader;   
  2. import java.io.IOException;   
  3. import java.io.InputStreamReader;   
  4. import java.io.UnsupportedEncodingException;   
  5. import java.net.URLEncoder;   
  6. import java.util.ArrayList;   
  7. import java.util.List;   
  8. import java.util.Map;   
  9. import org.apache.http.HttpResponse;   
  10. import org.apache.http.HttpStatus;   
  11. import org.apache.http.NameValuePair;   
  12. import org.apache.http.client.ClientProtocolException;   
  13. import org.apache.http.client.HttpClient;   
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;   
  15. import org.apache.http.client.methods.HttpGet;   
  16. import org.apache.http.client.methods.HttpPost;   
  17. import org.apache.http.client.methods.HttpUriRequest;   
  18. import org.apache.http.impl.client.DefaultHttpClient;   
  19. import org.apache.http.message.BasicNameValuePair;   
  20. import android.os.Handler;   
  21. import android.util.Log;   
  22. public class HttpConnectionUtil {   
  23.     public static enum HttpMethod {GET, POST}   
  24.        
  25.     public void asyncConnect(final String url, final HttpMethod method, final HttpConnectionCallback callback) {   
  26.         asyncConnect(url, null, method, callback);   
  27.     }   
  28.        
  29.     public void syncConnect(final String url, final HttpMethod method, final HttpConnectionCallback callback) {   
  30.         syncConnect(url, null, method, callback);   
  31.     }   
  32.        
  33.     public void asyncConnect(final String url, final Map<String, String> params,    
  34.             final HttpMethod method, final HttpConnectionCallback callback) {   
  35.         Handler handler = new Handler();   
  36.         Runnable runnable = new Runnable() {   
  37.             public void run() {   
  38.                 syncConnect(url, params, method, callback);   
  39.             }   
  40.         };   
  41.         handler.post(runnable);   
  42.     }   
  43.        
  44.     public void syncConnect(final String url, final Map<String, String> params,    
  45.             final HttpMethod method, final HttpConnectionCallback callback) {   
  46.         String json = null;   
  47.         BufferedReader reader = null;   
  48.            
  49.         try {   
  50.             HttpClient client = new DefaultHttpClient();   
  51.             HttpUriRequest request = getRequest(url, params, method);   
  52.             HttpResponse response = client.execute(request);   
  53.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
  54.                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));   
  55.                 StringBuilder sb = new StringBuilder();   
  56.                 for (String s = reader.readLine(); s != null; s = reader.readLine()) {   
  57.                     sb.append(s);   
  58.                 }   
  59.                 json = sb.toString();   
  60.             }   
  61.         } catch (ClientProtocolException e) {   
  62.             Log.e("HttpConnectionUtil", e.getMessage(), e);   
  63.         } catch (IOException e) {   
  64.             Log.e("HttpConnectionUtil", e.getMessage(), e);   
  65.         } finally {   
  66.             try {   
  67.                 if (reader != null) {   
  68.                     reader.close();   
  69.                 }   
  70.             } catch (IOException e) {   
  71.                 // ignore me   
  72.             }   
  73.         }   
  74.         callback.execute(json);   
  75.     }   
  76.        
  77.     private HttpUriRequest getRequest(String url, Map<String, String> params, HttpMethod method) {   
  78.         if (method.equals(HttpMethod.POST)) {   
  79.             List<NameValuePair> listParams = new ArrayList<NameValuePair>();   
  80.             if (params != null) {   
  81.                 for (String name : params.keySet()) {   
  82.                     listParams.add(new BasicNameValuePair(name, params.get(name)));   
  83.                 }   
  84.             }   
  85.             try {   
  86.                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listParams);   
  87.                 HttpPost request = new HttpPost(url);   
  88.                 request.setEntity(entity);   
  89.                 return request;   
  90.             } catch (UnsupportedEncodingException e) {   
  91.                 // Should not come here, ignore me.   
  92.                 throw new java.lang.RuntimeException(e.getMessage(), e);   
  93.             }   
  94.         } else {   
  95.             if (url.indexOf("?") < 0) {   
  96.                 url += "?";   
  97.             }   
  98.             if (params != null) {   
  99.                 for (String name : params.keySet()) {   
  100.                     url += "&" + name + "=" + URLEncoder.encode(params.get(name));   
  101.                 }   
  102.             }   
  103.             HttpGet request = new HttpGet(url);   
  104.             return request;   
  105.         }   
  106.     }   
  107. }   

HttpConnectionCallback类是一个回调类,用来处理请求完毕后的逻辑。

  1. public interface HttpConnectionCallback {   
  2.     /**  
  3.      * Call back method will be execute after the http request return.  
  4.      * @param response the response of http request.   
  5.      * The value will be null if any error occur.  
  6.      */  
  7.     void execute(String response);   
  8. }  

相关内容