现在的位置: 首页 > 综合 > 正文

利用android自带http包进行网络请求

2013年09月01日 ⁄ 综合 ⁄ 共 5497字 ⁄ 字号 评论关闭

转载自http://dai-lm.iteye.com/blog/1160191

1. 建立一个连接配置类

  1. class UserAgentConfig {  
  2.     public String host;  
  3.     public String scheme = "http";  
  4.     public int port = 80;  
  5.     public int timeoutConnection = 3000;  
  6.     public int timeoutSocket = 20000;  
  7.     public String username = "";  
  8.     public String password = "";  

2. 封装请求类

  1. public class HttpRequest {  
  2.   
  3.     /** 
  4.      * get "Stream" as response only based on URL 
  5.      *  
  6.      * @param strUrl 
  7.      * @return 
  8.      */  
  9.     public static InputStream getStream(String strUrl) {  
  10.   
  11.         InputStream input = null;  
  12.   
  13.         try {  
  14.             URL url = new URL(strUrl);  
  15.             HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();  
  16.             input = urlCon.getInputStream();  
  17.         } catch (IOException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.   
  21.         return input;  
  22.     }  
  23.   
  24.     /** 
  25.      * get "Stream" as response 
  26.      *  
  27.      * @param url       request URL 
  28.      * @param config    connection config 
  29.      * @param params    parameter for post method 
  30.      * @return response in stream 
  31.      * @throws IOException  
  32.      * @throws IllegalStateException  
  33.      */  
  34.     public static InputStream getStream(String url, UserAgentConfig config,  
  35.             List<BasicNameValuePair> params) {  
  36.   
  37.         HttpEntity entity = httprequest(url, config, params);  
  38.         InputStream ret = null;  
  39.   
  40.         if (entity != null) {  
  41.             try {  
  42.                 byte[] b = EntityUtils.toByteArray(entity);  
  43.                 ret = new ByteArrayInputStream(b);   
  44.             } catch (Exception e) {  
  45.                 e.printStackTrace();  
  46.             } finally {  
  47.                 release(entity);  
  48.             }  
  49.         }  
  50.   
  51.         return ret;  
  52.     }  
  53.   
  54.     /** 
  55.      * get "String" as response 
  56.      *  
  57.      * @param url 
  58.      * @param config 
  59.      * @param params 
  60.      * @return 
  61.      */  
  62.     public static String getString(String url, UserAgentConfig config,  
  63.             List<BasicNameValuePair> params) {  
  64.   
  65.         HttpEntity entity = httprequest(url, config, params);  
  66.         String ret = null;  
  67.   
  68.         if (entity != null) {  
  69.             try {  
  70.                 ret = EntityUtils.toString(entity);  
  71.             } catch (Exception e) {  
  72.                 e.printStackTrace();  
  73.             } finally {  
  74.                 release(entity);  
  75.             }  
  76.         }  
  77.   
  78.         return ret;  
  79.     }  
  80.   
  81.     private static void release(HttpEntity entity) {  
  82.         try {  
  83.             entity.consumeContent();  
  84.         } catch (IOException e) {  
  85.             e.printStackTrace();  
  86.         }  
  87.     }  
  88.   
  89.     /** 
  90.      * get "HttpEntity" as response 
  91.      *  
  92.      * @param url       request URL 
  93.      * @param config    connection config 
  94.      * @param params    parameter for post method 
  95.      * @return  
  96.      */  
  97.     private static HttpEntity httprequest(String url, UserAgentConfig config,  
  98.             List<BasicNameValuePair> params) {  
  99.   
  100.         DefaultHttpClient client = null;  
  101.         HttpEntity entity = null;  
  102.   
  103.         try {  
  104.             BasicHttpParams httpParameters = new BasicHttpParams();  
  105.   
  106.             // set connection timeout  
  107.             HttpConnectionParams.setConnectionTimeout(httpParameters,  
  108.                     config.timeoutConnection);  
  109.             HttpConnectionParams.setSoTimeout(httpParameters,  
  110.                     config.timeoutSocket);  
  111.   
  112.             client = new DefaultHttpClient(httpParameters);  
  113.   
  114.             // retry 3 times  
  115.             DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3true);  
  116.             client.setHttpRequestRetryHandler(retryHandler);  
  117.   
  118.             // set username & password if available  
  119.             if (!("".equals(config.username) && "".equals(config.password))) {  
  120.                 AuthScope as = new AuthScope(config.host, config.port);  
  121.                 UsernamePasswordCredentials upc = new UsernamePasswordCredentials(  
  122.                         config.username, config.password);  
  123.   
  124.                 client.getCredentialsProvider().setCredentials(as, upc);  
  125.             }  
  126.   
  127.             BasicHttpContext localContext = new BasicHttpContext();  
  128.   
  129.             BasicScheme basicAuth = new BasicScheme();  
  130.             localContext.setAttribute("preemptive-auth", basicAuth);  
  131.   
  132.             HttpHost targetHost = new HttpHost(config.host, config.port,  
  133.                     config.scheme);  
  134.   
  135.             // check get or post method by params  
  136.             HttpRequestBase method = null;  
  137.             if (params == null) {  
  138.                 method = new HttpGet(url);  
  139.             } else {  
  140.                 method = new HttpPost(url);  
  141.                 ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params,  
  142.                         "utf-8"));  
  143.             }  
  144.             method.setHeader("Content-Type""application/xml");  
  145.   
  146.             HttpResponse response = client.execute(targetHost, method,  
  147.                     localContext);  
  148.   
  149.             entity = response.getEntity();  
  150.   
  151.         } catch (Exception e) {  
  152.             e.printStackTrace();  
  153.         }  
  154.   
  155.         return entity;  
  156.     }  

3. 调用
GET请求

  1. String url = "...";  
  2.   
  3. UserAgentConfig config = new UserAgentConfig();  
  4. config.host = "...";  
  5.   
  6. test(url, config, null); 

POST请求

  1. String url = "...";  
  2.   
  3. UserAgentConfig config = new UserAgentConfig();  
  4. config.host = "...";  
  5. config.username = "...";  
  6. config.password = "...";  
  7.   
  8. ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();  
  9. params.add(new BasicNameValuePair("...""..."));  
  10. ...  
  11.   
  12. test(url, config, params); 

抱歉!评论已关闭.