`
endual
  • 浏览: 3506699 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Android----http请求工具类(转)

 
阅读更多

 

Android----http请求工具类

分类: Android开发 243人阅读 评论(0) 收藏 举报

项目中客户端与服务器端采用http请求进行交互,在这里我把http请求的工具类贴出来。

该工具类采用的是HttpClients框架,HTTP保存方式有两种选择 :一种:整个应用 只创建 一个HttpClient对象,然后保存在整个程序中去。此情况无法创建多线程中应用。
另一种:随时创建HttpClient对象。系统自动保存Session就行。此情况可能对系统资源消耗利害
 用完之后请随时销毁HttpClient,避免系统中存在很多HttpClient对象。在这里我采用的是第二种。

包含两个java文件,第一个是主要的请求工具类文件,第二个主要是保存请求的session,下面见代码:

  1. package com.hlj.padtwo.util.util_public.httputil;  
  2.   
  3.   
  4.   
  5. import java.io.File;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.net.URLEncoder;  
  9. import java.nio.charset.Charset;  
  10. import java.util.ArrayList;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Map;  
  15.   
  16. import javax.net.ssl.SSLHandshakeException;  
  17.   
  18. import org.apache.http.Header;  
  19. import org.apache.http.HttpEntityEnclosingRequest;  
  20. import org.apache.http.HttpHost;  
  21. import org.apache.http.HttpRequest;  
  22. import org.apache.http.HttpResponse;  
  23. import org.apache.http.NameValuePair;  
  24. import org.apache.http.NoHttpResponseException;  
  25. import org.apache.http.client.ClientProtocolException;  
  26. import org.apache.http.client.CookieStore;  
  27. import org.apache.http.client.HttpRequestRetryHandler;  
  28. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  29. import org.apache.http.client.methods.HttpGet;  
  30. import org.apache.http.client.methods.HttpPost;  
  31. import org.apache.http.client.params.HttpClientParams;  
  32. import org.apache.http.conn.params.ConnRouteParams;  
  33. import org.apache.http.entity.mime.HttpMultipartMode;  
  34. import org.apache.http.entity.mime.MultipartEntity;  
  35. import org.apache.http.entity.mime.content.ContentBody;  
  36. import org.apache.http.entity.mime.content.FileBody;  
  37. import org.apache.http.entity.mime.content.StringBody;  
  38. import org.apache.http.impl.client.DefaultHttpClient;  
  39. import org.apache.http.params.BasicHttpParams;  
  40. import org.apache.http.params.HttpConnectionParams;  
  41. import org.apache.http.params.HttpParams;  
  42. import org.apache.http.protocol.ExecutionContext;  
  43. import org.apache.http.protocol.HTTP;  
  44. import org.apache.http.protocol.HttpContext;  
  45. import org.apache.http.util.EntityUtils;  
  46.   
  47. import android.app.Activity;  
  48. import android.content.Context;  
  49. import android.widget.Toast;  
  50.   
  51. import com.hlj.padtwo.util.application.MyApplication;  
  52.   
  53.   
  54. /*** 
  55.  * Http通信中的POST和GET请求方式的不同。GET把参数放在URL字符串后面,传递给服务器。 
  56.  * 而POST方法的参数是放在Http请求中,主要用于手机对Http访问提供公共的访问类对象。 
  57.  * @author hlj 
  58.  * @date 
  59.  * @versionn 1.0 
  60.  **/  
  61. public class HttpClients {  
  62.     /** 执行downfile后,得到下载文件的大小 */  
  63.     private long contentLength;  
  64.     /** 返回连接失败信息 **/  
  65.     private String strResult = "服务器无法连接,请检查网络";  
  66.   
  67.     /** http 请求头参数 **/  
  68.     private HttpParams httpParams;  
  69.     /** httpClient 对象 **/  
  70.     private DefaultHttpClient httpClient;  
  71.   
  72.   
  73.     /** 得到上下文 **/  
  74.     private Context context;  
  75.     private Activity activity = null;  
  76.   
  77.     public HttpClients(Activity act) {  
  78.         this.context = act.getBaseContext();  
  79.         this.activity = act;  
  80.         getHttpClient();  
  81.     }  
  82.   
  83.     /** 
  84.      * 提供GET形式的访问网络请求 doGet 参数示例: Map params=new HashMap(); 
  85.      * params.put("usename","helijun"); params.put("password","123456"); 
  86.      * httpClient.doGet(url,params); 
  87.      *  
  88.      * @param url 
  89.      *            请求地址 
  90.      * @param params 
  91.      *            请求参数 
  92.      * @return 返回 String jsonResult; 
  93.      *  
  94.      * **/  
  95.     @SuppressWarnings("unchecked")  
  96.     public String doGet(String url, Map params) {  
  97.         /** 建立HTTPGet对象 **/  
  98.         String paramStr = "";  
  99.         if (params == null)  
  100.             params = new HashMap();  
  101.         /** 迭代请求参数集合 **/  
  102.         Iterator iter = params.entrySet().iterator();  
  103.         while (iter.hasNext()) {  
  104.             Map.Entry entry = (Map.Entry) iter.next();  
  105.             Object key = entry.getKey();  
  106.             String val = nullToString(entry.getValue());  
  107.             paramStr += paramStr = "&" + key + "=" + URLEncoder.encode(val);  
  108.         }  
  109.         if (!paramStr.equals("")) {  
  110.             paramStr = paramStr.replaceFirst("&""?");  
  111.             url += paramStr;  
  112.         }  
  113.         return doGet(url);  
  114.     }  
  115.   
  116.     /** 
  117.      * 提供GET形式的访问网络请求 doGet 参数示例: Map params=new HashMap(); 
  118.      * params.put("usename","gongshuanglin"); params.put("password","123456"); 
  119.      * httpClient.doGet(url,params); 
  120.      *  
  121.      * @param url 
  122.      *            请求地址 
  123.      * @param params 
  124.      *            请求参数 
  125.      * @return 返回 String jsonResult; 
  126.      *  
  127.      */  
  128.     public String doGet(String url, List<NameValuePair> params) {  
  129.         /** 建立HTTPGet对象 **/  
  130.         String paramStr = "";  
  131.         if (params == null)  
  132.             params = new ArrayList<NameValuePair>();  
  133.         /** 迭代请求参数集合 **/  
  134.   
  135.         for (NameValuePair obj : params) {  
  136.             paramStr += paramStr = "&" + obj.getName() + "="  
  137.                     + URLEncoder.encode(obj.getValue());  
  138.         }  
  139.         if (!paramStr.equals("")) {  
  140.             paramStr = paramStr.replaceFirst("&""?");  
  141.             url += paramStr;  
  142.         }  
  143.         return doGet(url);  
  144.     }  
  145.   
  146.     /** 
  147.      * 提供GET形式的访问网络请求 doGet 参数示例: 
  148.      *  
  149.      * @param url 
  150.      *            请求地址 
  151.      * @return 返回 String jsonResult; 
  152.      *  
  153.      */  
  154.     public String doGet(String url) {  
  155.         /** 创建HttpGet对象 **/  
  156.         HttpGet httpRequest = new HttpGet(url);  
  157.         httpRequest.setHeaders(this.getHeader());  
  158.         try {  
  159.             /** 保持会话Session **/  
  160.             /** 设置Cookie **/  
  161.             MyHttpCookies li = new MyHttpCookies(context);  
  162.             CookieStore cs = li.getuCookie();  
  163.             /** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/  
  164.             if (cs != null) {  
  165.                 httpClient.setCookieStore(li.getuCookie());  
  166.             }  
  167.   
  168.             /** 保持会话Session end **/  
  169.   
  170.             /* 发送请求并等待响应 */  
  171.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  172.             /* 若状态码为200 ok */  
  173.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  174.                 /* 读返回数据 */  
  175.                 strResult = EntityUtils.toString(httpResponse.getEntity());  
  176.   
  177.                 /** 执行成功之后得到 **/  
  178.                 /** 成功之后把返回成功的Cookis保存APP中 **/  
  179.                 // 请求成功之后,每次都设置Cookis。保证每次请求都是最新的Cookis  
  180.                 li.setuCookie(httpClient.getCookieStore());  
  181.   
  182.             } else {  
  183.                 strResult = "Error Response: "  
  184.                         + httpResponse.getStatusLine().toString();  
  185.             }  
  186.         } catch (ClientProtocolException e) {  
  187.             strResult = nullToString(e.getMessage());  
  188.             e.printStackTrace();  
  189.         } catch (IOException e) {  
  190.             strResult = nullToString(e.getMessage());  
  191.             e.printStackTrace();  
  192.         } catch (Exception e) {  
  193.             strResult = nullToString(e.getMessage());  
  194.             e.printStackTrace();  
  195.         } finally {  
  196.             httpRequest.abort();  
  197.             this.shutDownClient();  
  198.         }  
  199.         return strResult;  
  200.     }  
  201.   
  202.     /** 
  203.      * 提供Post形式的访问网络请求 Post 参数示例: doPost 参数示例 List<NameValuePair> paramlist = 
  204.      * new ArrayList<NameValuePair>(); paramlist(new BasicNameValuePair("email", 
  205.      * "xxx@123.com")); paramlist(new BasicNameValuePair("address", "123abc")); 
  206.      * httpClient.doPost(url,paramlist); 
  207.      *  
  208.      * @param url 
  209.      *            请求地址 
  210.      * @param params 
  211.      *            请求参数 
  212.      * @return 返回 String jsonResult; 
  213.      * **/  
  214.   
  215.     public String doPost(String url, List<NameValuePair> params) {  
  216.         /* 建立HTTPPost对象 */  
  217.   
  218.         HttpPost httpRequest = new HttpPost(url);  
  219.         // 设置请求Header信息、  
  220.         httpRequest.setHeaders(this.getHeader());  
  221.         try {  
  222.             /** 添加请求参数到请求对象 */  
  223. //          boolean upFileFlag = false;// 是否有文件上传  
  224. //          MultipartEntity mpEntity = new MultipartEntity(  
  225. //                  HttpMultipartMode.BROWSER_COMPATIBLE);  
  226. //          for (NameValuePair param : params) {  
  227. //              ContentBody contentBody = null;  
  228. //              File file = new File(param.getValue());  
  229. //              if (file.isFile()) {  
  230. //                  contentBody = new FileBody(file);  
  231. //                  upFileFlag = true;  
  232. //              } else {  
  233. //                  contentBody = new StringBody(param.getValue(), Charset  
  234. //                          .forName(HTTP.UTF_8));  
  235. //              }  
  236. //              mpEntity.addPart(param.getName(), contentBody);  
  237. //          }  
  238. //  
  239. //          if (upFileFlag == true) {// 文件 上传  
  240. //              httpRequest.setEntity(mpEntity);  
  241. //          } else {  
  242.                 /** 添加请求参数到请求对象 */  
  243.                 httpRequest.setEntity(new UrlEncodedFormEntity(params,  
  244.                         HTTP.UTF_8));  
  245. //          }  
  246.   
  247.             /** 保持会话Session **/  
  248.             /** 设置Cookie **/  
  249.                 MyHttpCookies li = new MyHttpCookies(context);  
  250.             CookieStore cs = li.getuCookie();  
  251.             /** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/  
  252.             if (cs != null) {  
  253.                 httpClient.setCookieStore(li.getuCookie());  
  254.             }  
  255.   
  256.             /** 保持会话Session end **/  
  257.   
  258.             /** 发送请求并等待响应 */  
  259.   
  260.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  261.               
  262.             /** 若状态码为200 ok */  
  263.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  264.                 /* 读返回数据 */  
  265.                 strResult = EntityUtils.toString(httpResponse.getEntity());  
  266.   
  267.                 /** 执行成功之后得到 **/  
  268.                 /** 成功之后把返回成功的Cookis保存APP中 **/  
  269.                 // 请求成功之后,每次都设置Cookis。保证每次请求都是最新的Cookis  
  270.                 li.setuCookie(httpClient.getCookieStore());  
  271.   
  272.                 /** 设置Cookie end **/  
  273.             } else {  
  274.                 strResult = "Error Response: "  
  275.                         + httpResponse.getStatusLine().toString();  
  276.             }  
  277.         } catch (ClientProtocolException e) {  
  278.             strResult = "";  
  279. //          strResult = e.getMessage().toString();  
  280.             e.printStackTrace();  
  281.         } catch (IOException e) {  
  282.             strResult = "";  
  283. //          strResult = e.getMessage().toString();  
  284.             e.printStackTrace();  
  285.         } catch (Exception e) {  
  286.             strResult = "";  
  287. //          strResult = e.getMessage().toString();  
  288.             e.printStackTrace();  
  289.         } finally {  
  290.             httpRequest.abort();  
  291.             this.shutDownClient();  
  292.         }  
  293.         return strResult;  
  294.     }  
  295.   
  296.     /** 得到 apache http HttpClient对象 **/  
  297.     public DefaultHttpClient getHttpClient() {  
  298.   
  299.         /** 创建 HttpParams 以用来设置 HTTP 参数 **/  
  300.   
  301.         httpParams = new BasicHttpParams();  
  302.   
  303.         /** 设置连接超时和 Socket 超时,以及 Socket 缓存大小 **/  
  304.   
  305.         HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);  
  306.   
  307.         HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);  
  308.   
  309.         HttpConnectionParams.setSocketBufferSize(httpParams, 8192);  
  310.   
  311.         HttpClientParams.setRedirecting(httpParams, true);  
  312.   
  313.         /** 
  314.          * 创建一个 HttpClient 实例 //增加自动选择网络,自适应cmwap、CMNET、wifi或3G 
  315.          */  
  316.         MyHttpCookies li = new MyHttpCookies(context);  
  317.         String proxyStr = li.getHttpProxyStr();  
  318.         if (proxyStr != null && proxyStr.trim().length() > 0) {  
  319.             HttpHost proxy = new HttpHost(proxyStr, 80);  
  320.             httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,  
  321.                     proxy);  
  322.         }  
  323.         /** 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient **/  
  324.   
  325.         httpClient = new DefaultHttpClient(httpParams);  
  326.         httpClient.setHttpRequestRetryHandler(requestRetryHandler);  
  327.           
  328.         return httpClient;  
  329.   
  330.     }  
  331.   
  332.     /** 得到设备信息、系统版本、驱动类型 **/  
  333.     private Header[] getHeader() {  
  334.         /** 请求头信息 end **/  
  335.         MyHttpCookies li = new MyHttpCookies(context);  
  336.         return li.getHttpHeader();  
  337.     }  
  338.   
  339.     /** 销毁HTTPCLient **/  
  340.     public void shutDownClient() {  
  341.         httpClient.getConnectionManager().shutdown();  
  342.     }  
  343.   
  344. //  /**  
  345. //   * 提供GET形式的访问网络请求 doGet 参数示例:  
  346. //   *   
  347. //   * @param url  
  348. //   *            请求地址  
  349. //   * @return 返回 String jsonResult;  
  350. //   *   
  351. //   */  
  352. //  public InputStream doDownFile(String url) {  
  353. //      /** 创建HttpGet对象 **/  
  354. //      HttpGet httpRequest = new HttpGet(url);  
  355. //      httpRequest.setHeaders(this.getHeader());  
  356. //      try {  
  357. //          /** 保持会话Session **/  
  358. //          /** 设置Cookie **/  
  359. //          MyHttpCookies li = new MyHttpCookies(context);  
  360. //          CookieStore cs = li.getuCookie();  
  361. //          /** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/  
  362. //          if (cs != null) {  
  363. //              httpClient.setCookieStore(li.getuCookie());  
  364. //          }  
  365. //          /** 保持会话Session end **/  
  366. //          /* 发送请求并等待响应 */  
  367. //          HttpResponse httpResponse = httpClient.execute(httpRequest);  
  368. //          /* 若状态码为200 ok */  
  369. //          if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  370. //              /** 执行成功之后得到 **/  
  371. //              /** 成功之后把返回成功的Cookis保存APP中 **/  
  372. //              // 请求成功之后,每次都设置Cookis。保证每次请求都是最新的Cookis  
  373. //              li.setuCookie(httpClient.getCookieStore());  
  374. //              this.contentLength = httpResponse.getEntity()  
  375. //                      .getContentLength();  
  376. //              /* 读返回数据 */  
  377. //              return httpResponse.getEntity().getContent();  
  378. //          } else {  
  379. //              strResult = "Error Response: "  
  380. //                      + httpResponse.getStatusLine().toString();  
  381. //          }  
  382. //      } catch (ClientProtocolException e) {  
  383. //          strResult = e.getMessage().toString();  
  384. //          e.printStackTrace();  
  385. //      } catch (IOException e) {  
  386. //          strResult = e.getMessage().toString();  
  387. //          e.printStackTrace();  
  388. //      } catch (Exception e) {  
  389. //          strResult = e.getMessage().toString();  
  390. //          e.printStackTrace();  
  391. //      } finally {  
  392. //          // httpRequest.abort();  
  393. //          // this.shutDownClient();  
  394. //      }  
  395. //      this.contentLength = 0;  
  396. //      return null;  
  397. //  }  
  398.   
  399.     /** 
  400.      * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复 
  401.      */  
  402.     private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {  
  403.         // 自定义的恢复策略  
  404.         public boolean retryRequest(IOException exception, int executionCount,  
  405.                 HttpContext context) {  
  406.             // 设置恢复策略,在发生异常时候将自动重试N次  
  407.             if (executionCount >= 3) {  
  408.                 // 如果超过最大重试次数,那么就不要继续了  
  409.                 return false;  
  410.             }  
  411.             if (exception instanceof NoHttpResponseException) {  
  412.                 // 如果服务器丢掉了连接,那么就重试  
  413.                 return true;  
  414.             }  
  415.             if (exception instanceof SSLHandshakeException) {  
  416.                 // 不要重试SSL握手异常  
  417.                 return false;  
  418.             }  
  419.             HttpRequest request = (HttpRequest) context  
  420.                     .getAttribute(ExecutionContext.HTTP_REQUEST);  
  421.             boolean idempotent = (request instanceof HttpEntityEnclosingRequest);  
  422.             if (!idempotent) {  
  423.                 // 如果请求被认为是幂等的,那么就重试  
  424.                 return true;  
  425.             }  
  426.             return false;  
  427.         }  
  428.     };  
  429.   
  430.     public long getContentLength() {  
  431.         return contentLength;  
  432.     }  
  433.   
  434.     /** 
  435.      * 假如obj对象 是null返回"" 
  436.      * @param obj 
  437.      * @return 
  438.      */  
  439.     public static String nullToString(Object obj){  
  440.         if(obj==null){  
  441.             return "";  
  442.         }  
  443.         return obj.toString();  
  444.     }  
  445. }  

 

  1. package com.hlj.padtwo.util.util_public.httputil;  
  2.   
  3.   
  4.   
  5. import org.apache.http.Header;  
  6. import org.apache.http.client.CookieStore;  
  7. import org.apache.http.message.BasicHeader;  
  8.   
  9. import android.content.Context;  
  10. import android.database.Cursor;  
  11. import android.net.Uri;  
  12. import android.net.wifi.WifiManager;  
  13.   
  14. /** 
  15.  * http请求的缓存和一些公用的参数 
  16.  * @author helijun 
  17.  * 
  18.  */  
  19. public class MyHttpCookies {  
  20.     /** 每页数据显示最大数 */  
  21.     private static int pageSize = 10;  
  22.     /** 当前会话后的cokie信息 */  
  23.     private static CookieStore uCookie = null;  
  24.     /** 公用的HTTP提示头信息 */  
  25.     private static Header[] httpHeader;  
  26.     /** HTTP连接的网络节点 */  
  27.     private static String httpProxyStr;  
  28.     /**http请求的公用url部分**/  
  29.     public static String baseurl = "http://192.168.50.56:5056/River";  
  30.     /**上下文对象**/  
  31.     Context context;  
  32.       
  33.     public MyHttpCookies(Context context){  
  34.         this.context = context;  
  35.         /** y设置请求头 **/  
  36.         /** y设置请求头 **/  
  37.         Header[] header = {  
  38.                 new BasicHeader("PagingRows", String.valueOf(pageSize)) };  
  39.         httpHeader = header;  
  40.     }  
  41.       
  42.     /** 
  43.      * 增加自动选择网络,自适应cmwap、CMNET、wifi或3G 
  44.      */  
  45.     @SuppressWarnings("static-access")  
  46.     public void initHTTPProxy() {  
  47.         WifiManager wifiManager = (WifiManager) (context.getSystemService(context.WIFI_SERVICE));  
  48.         if (!wifiManager.isWifiEnabled()) {  
  49.             Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点  
  50.             Cursor mCursor =context. getContentResolver().query(uri, null, null, null,  
  51.                     null);  
  52.             if (mCursor != null) {  
  53.                 mCursor.moveToNext(); // 游标移至第一条记录,当然也只有一条  
  54.                 httpProxyStr = mCursor.getString(mCursor  
  55.                         .getColumnIndex("proxy"));  
  56.             }  
  57.         } else {  
  58.             httpProxyStr = null;  
  59.         }  
  60.     }  
  61.       
  62.     public int getPageSize() {  
  63.         return pageSize;  
  64.     }  
  65.   
  66.     public void setPageSize(int pageSize) {  
  67.         this.pageSize = pageSize;  
  68.     }  
  69.   
  70.     public CookieStore getuCookie() {  
  71.         return uCookie;  
  72.     }  
  73.   
  74.     public void setuCookie(CookieStore uCookie) {  
  75.         this.uCookie = uCookie;  
  76.     }  
  77.   
  78.   
  79.     public Header[] getHttpHeader() {  
  80.         return httpHeader;  
  81.     }  
  82.   
  83.     public String getHttpProxyStr() {  
  84.         return httpProxyStr;  
  85.     }  
  86. }  
分享到:
评论
1 楼 农民柏柏 2013-03-11  
  

相关推荐

Global site tag (gtag.js) - Google Analytics