分享

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

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

修改了一下,可以自定义请求的Header,增加了对POST表单数据的支持。

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.     private String mUrl;  
  4.     private UserAgentConfig mConfig = null;  
  5.     private HashMap<String, String> mHeaders = null;  
  6.     private HttpEntity mBody = null;  
  7.     private int mStatus = -1;  
  8.   
  9.     public HttpRequest(String url) {  
  10.         mUrl = url;  
  11.     }  
  12.   
  13.     public void addHeader(String key, String value) {  
  14.         if (mHeaders == null)  
  15.             mHeaders = new HashMap<String, String>();  
  16.   
  17.         mHeaders.put(key, value);  
  18.     }  
  19.   
  20.     public void clearHeader() {  
  21.         mHeaders.clear();  
  22.         mHeaders = null;  
  23.     }  
  24.   
  25.     public void setConfig(UserAgentConfig config) {  
  26.         mConfig = config;  
  27.     }  
  28.   
  29.     public void setPostBody(List<BasicNameValuePair> body) {  
  30.         try {  
  31.             mBody = new UrlEncodedFormEntity(body, "utf-8");  
  32.         } catch (UnsupportedEncodingException e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.     }  
  36.   
  37.     public void setPostBody(String body) {  
  38.         try {  
  39.             mBody = new StringEntity(body);  
  40.         } catch (UnsupportedEncodingException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.   
  45.     public void execute() throws ClientProtocolException, IOException {  
  46.         httprequest();  
  47.     }  
  48.   
  49.     public int getStatusCode() {  
  50.         return mStatus;  
  51.     }  
  52.   
  53.     /** 
  54.      * get "Stream" as response 
  55.      *  
  56.      * @return response in stream 
  57.      * @throws IOException 
  58.      * @throws ClientProtocolException 
  59.      */  
  60.     public InputStream getStream() throws ClientProtocolException, IOException {  
  61.   
  62.         HttpEntity entity = httprequest();  
  63.         InputStream ret = null;  
  64.   
  65.         if (entity != null) {  
  66.             try {  
  67.                 byte[] b = EntityUtils.toByteArray(entity);  
  68.                 ret = new ByteArrayInputStream(b);  
  69.             } finally {  
  70.                 release(entity);  
  71.             }  
  72.         }  
  73.   
  74.         return ret;  
  75.     }  
  76.   
  77.     /** 
  78.      * get "String" as response 
  79.      *  
  80.      * @return response in string 
  81.      * @throws IOException 
  82.      * @throws ClientProtocolException 
  83.      */  
  84.     public String getString() throws ClientProtocolException, IOException {  
  85.   
  86.         HttpEntity entity = httprequest();  
  87.         String ret = null;  
  88.   
  89.         if (entity != null) {  
  90.             try {  
  91.                 ret = EntityUtils.toString(entity);  
  92.             } finally {  
  93.                 release(entity);  
  94.             }  
  95.         }  
  96.   
  97.         return ret;  
  98.     }  
  99.   
  100.     /** 
  101.      * release connection resource 
  102.      *  
  103.      * @param entity 
  104.      */  
  105.     private static void release(HttpEntity entity) {  
  106.         try {  
  107.             entity.consumeContent();  
  108.         } catch (IOException e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.     }  
  112.   
  113.     /** 
  114.      * get "HttpEntity" as response 
  115.      *  
  116.      * @return 
  117.      * @throws IOException 
  118.      * @throws ClientProtocolException 
  119.      */  
  120.     private HttpEntity httprequest() throws ClientProtocolException,  
  121.             IOException {  
  122.   
  123.         System.out.println(mUrl);  
  124.   
  125.         DefaultHttpClient client = null;  
  126.         HttpEntity entity = null;  
  127.   
  128.         BasicHttpParams httpParameters = new BasicHttpParams();  
  129.   
  130.         if (mConfig != null) {  
  131.             // set connection timeout  
  132.             HttpConnectionParams.setConnectionTimeout(httpParameters,  
  133.                     mConfig.timeoutConnection);  
  134.         }  
  135.   
  136.         client = new DefaultHttpClient(httpParameters);  
  137.   
  138.         DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(  
  139.                 3, true);  
  140.         client.setHttpRequestRetryHandler(retryHandler);  
  141.   
  142.         // set username & password if available  
  143.         if (mConfig != null  
  144.                 && !(isEmpty(mConfig.username) && isEmpty(mConfig.password))) {  
  145.             AuthScope as = new AuthScope(mConfig.host, mConfig.port);  
  146.             UsernamePasswordCredentials upc = new UsernamePasswordCredentials(  
  147.                     mConfig.username, mConfig.password);  
  148.   
  149.             client.getCredentialsProvider().setCredentials(as, upc);  
  150.         }  
  151.   
  152.         // check get or post method by params  
  153.         HttpRequestBase method = null;  
  154.         if (mBody == null) {  
  155.             method = new HttpGet(mUrl);  
  156.         } else {  
  157.             method = new HttpPost(mUrl);  
  158.             ((HttpPost) method).setEntity(mBody);  
  159.         }  
  160.   
  161.         // set request header  
  162.         if (mHeaders != null) {  
  163.             Iterator<?> iter = mHeaders.entrySet().iterator();  
  164.             while (iter.hasNext()) {  
  165.                 Map.Entry<?, ?> entry = (Entry<?, ?>) iter.next();  
  166.                 String key = (String) entry.getKey();  
  167.                 String val = (String) entry.getValue();  
  168.                 method.setHeader(key, val);  
  169.             }  
  170.         }  
  171.   
  172.         // get response  
  173.         HttpResponse response = null;  
  174.         if (mConfig == null || isEmpty(mConfig.host) || isEmpty(mConfig.scheme)) {  
  175.             // only URL is available  
  176.             response = client.execute(method);  
  177.         } else {  
  178.             BasicHttpContext localContext = new BasicHttpContext();  
  179.   
  180.             BasicScheme basicAuth = new BasicScheme();  
  181.             localContext.setAttribute("preemptive-auth", basicAuth);  
  182.   
  183.             HttpHost targetHost = new HttpHost(mConfig.host, mConfig.port,  
  184.                     mConfig.scheme);  
  185.   
  186.             response = client.execute(targetHost, method, localContext);  
  187.         }  
  188.   
  189.         mStatus = response.getStatusLine().getStatusCode();  
  190.         entity = response.getEntity();  
  191.   
  192.         return entity;  
  193.     }  
  194.   
  195.     /** 
  196.      * Check the string is valuable or not 
  197.      *  
  198.      * @param s 
  199.      * @return true if s is null or s.length() == 0 false otherwise 
  200.      */  
  201.     private boolean isEmpty(String s) {  
  202.         return s == null || s.length() == 0;  
  203.     }  
  204. }  

3. 调用
GET请求
Java代码  收藏代码
  1. HttpRequest request = new HttpRequest("...");  
  2. request.execute();  

Java代码  收藏代码
  1. UserAgentConfig config = new UserAgentConfig();  
  2. config.host = "...";  
  3. config.username = "...";  
  4. config.password = "...";  
  5.   
  6. HttpRequest request = new HttpRequest("...");  
  7. request.setConfig(config);  
  8.   
  9. System.out.println(request.getString());  

POST请求
Java代码  收藏代码
  1. HttpRequest request = new HttpRequest("...");  
  2. request.addHeader("...", "...");  
  3. request.setPostBody("....");  
  4. request.execute();  
  5.   
  6. System.out.println(request.getStatusCode());  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多