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

用android 自带的包进行网络请求

2013年09月11日 ⁄ 综合 ⁄ 共 5532字 ⁄ 字号 评论关闭

目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)

1. 建立一个连接配置类

Java代码  收藏代码
  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 = "";  
  9. }  

2. 封装请求类

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

3. 调用
GET请求

Java代码  收藏代码
  1. String url = "...";  
  2. test(url, nullnull);  

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

POST请求

Java代码  收藏代码
  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); 

抱歉!评论已关闭.