Android HttpClient及连接管理器

超文本传输协议HTTP也许是当今互联网上使用的最重要的协议了。 尽管java.net包提供了基本通过HTTP访问资源的功能,但它没有提供全面的灵活性和其它很多应用程序需要的功能。

HttpClient就是寻求弥补这项空白的组件,通过提供一个有效的保持更新的功能丰富的软件包来实现客户端最新的HTTP标准和建议。 为扩展而设计同时为基本的HTTP协议提供强大的支持HttpClient组件也许就是构建HTTP客户端应用程序。

HttpClient它是一个客户端的HTTP通信实现库。HttpClient的目标是发送和接收HTTP报文。HttpClient不会去缓存内容,执行嵌 入在HTML页面中的javascript代码猜测内容类型重新格式化请求/重定向URI或者其它和HTTP运输无关的功能。 


1.执行请求

HttpClient 最重要的功能是执行HTTP方法。一个HTTP方法的执行包含一个或多个HTTP请求/HTTP响应交换,通常由HttpClient的内部来处理。而期 望用户提供一个要执行的请求对象,而HttpClient期望传输请求到目标服务器并返回对应的响应对象或者当执行不成功时抛出异常。 


2.中止请求 
在 一些情况下,由于目标服务器的高负载或客户端有很多活动的请求,那么HTTP请求执行会在预期的时间框内而失败。这时就可能不得不过早地中止请求,解除 封锁在I/O执行中的线程封锁。被HttpClient执行的HTTP请求可以在执行的任意阶段通过调用HttpUriRequest#abort()方 法而中止。这个方法是线程安全的,而且可以从任意线程中调用。当一个HTTP请求被中止时,它的执行线程就封锁在I/O操作中了而且保证通过抛出 InterruptedIOException异常来解锁。


3. 连接管理器关闭 

当一个HttpClient实例不再需要时而且即将走出使用范围,那么关闭连接管理器来保证由管理器保持活动的所有连接被关闭由连接分配的系统资源被释放是很重要的。 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. DefaultHttpClient httpclient = new DefaultHttpClient();   
  2. HttpGet httpget = new HttpGet("http://www.google.com/");   
  3. HttpResponse response = httpclient.execute(httpget);   
  4. HttpEntity entity = response.getEntity();   
  5. System.out.println(response.getStatusLine());   
  6. if (entity != null) {   
  7. entity.consumeContent();   
  8. }   
  9. httpclient.getConnectionManager().shutdown();  


4. 多线程执行请求 
当配备连接池管理器时比如ThreadSafeClientConnManager,HttpClient可以同时被用来执行多个请求使用多线程执行。 ThreadSafeClientConnManager 将会分配基于它的配置的连接。如果对于给定路由的所有连接都被租出了,那么连接的请求将会阻塞直到一个连接被释放回连接池。它可以通过设置 'http.conn-manager.timeout'为一个正数来保证连接管理器不会在连接请求执行时无限期的被阻塞。如果连接请求不能在给定的时间 周期内被响应,将会抛出ConnectionPoolTimeoutException异常。


5.使用单例HttpClient

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(当然它的功能远不止这些)。


比如你只需以下几行代码就能发出一个简单的GET请求并打印响应结果:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try {  
  2.         // 创建一个默认的HttpClient  
  3.         HttpClient httpclient =new DefaultHttpClient();  
  4.         // 创建一个GET请求  
  5.         HttpGet request =new HttpGet("www.google.com");  
  6.         // 发送GET请求,并将响应内容转换成字符串  
  7.         String response = httpclient.execute(request, new BasicResponseHandler());  
  8.         Log.v("response text", response);  
  9.     } catch (ClientProtocolException e) {  
  10.         e.printStackTrace();  
  11.     } catch (IOException e) {  
  12.         e.printStackTrace();  
  13.     }  

为什么要使用单例HttpClient?

对于已经和服务端建立了连接的应用来说,再次调用HttpClient进行网络数据传输时,就不必重新建立新连接了,而可以重用已经建立的连接。这样无疑可以减少开销,提升速度。
    在这个方面,Apache已经做了“连接管理”,默认情况下,就会尽可能的重用已有连接,因此,不需要客户端程序员做任何配置。只是需要注意,Apache的连接管理并不会主动释放建立的连接,需要程序员在不用的时候手动关闭连接。

这只是一段演示代码,实际的项目中的请求与响应处理会复杂一些,并且还要考虑到代码的容错性,但是这并不是本篇的重点。注意代码:

 HttpClient httpclient =new DefaultHttpClient();
在发出HTTP请求前,我们先创建了一个HttpClient对象。那么,在实际项目中,我们很可能在多处需要进行HTTP通信,这时候我们不需要为每个请求都创建一个新的HttpClient。因为之前已经提到,HttpClient就像一个小型的浏览器,对于整个应用,我们只需要一个HttpClient就够了。看到这里,一定有人心里想,这有什么难的,用单例啊!!就像这样:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. publicclass CustomerHttpClient {  
  2.     privatestatic HttpClient customerHttpClient;  
  3.       
  4.     private CustomerHttpClient() {  
  5.     }  
  6.       
  7.     publicstatic HttpClient getHttpClient() {  
  8.         if(null== customerHttpClient) {  
  9.             customerHttpClient =new DefaultHttpClient();  
  10.         }  
  11.         return customerHttpClient;  
  12.     }  
  13. }  

那么,哪里不对劲呢?或者说做的还不够完善呢?

多线程!试想,现在我们的应用程序使用同一个HttpClient来管理所有的Http请求,一旦出现并发请求,那么一定会出现多线程的问题。这就好像我们的浏览器只有一个标签页却有多个用户,A要上google,B要上baidu,这时浏览器就会忙不过来了。幸运的是,HttpClient提供了创建线程安全对象的API,帮助我们能很快地得到线程安全的“浏览器”。


解决多线程问题:

使用ThreadSafeClientConnManager管理线程池,如果应用程序采用了多线程进行网络访问,则应该使用Apache封装好的线程安全管理类ThreadSafeClientConnManager来进行管理,这样能够更有效且更安全的管理多线程和连接池中的连接。

    (在网上也看到有人用MultiThreadedHttpConnectionManager进行线程安全管理的,后查了下Apache的API,发现MultiThreadedHttpConnectionManager是API 2.0中的类,而ThreadSafeClientConnManager是API 4.0中的类,比前者更新,所以选择使用ThreadSafeClientConnManager。另外,还看到有PoolingClientConnectionManager这个类,是API 4.2中的类,比ThreadSafeClientConnManager更新,但Android SDK中找不到该类。所以目前还是选择了ThreadSafeClientConnManager进行管理)


1)大量传输数据时,使用“请求流/响应流”的方式
    当需要传输大量数据时,不应使用字符串(strings)或者字节数组(byte arrays),因为它们会将数据缓存至内存。当数据过多,尤其在多线程情况下,很容易造成内存溢出(out of memory,OOM)。
    而HttpClient能够有效处理“实体流(stream)”。这些“流”不会缓存至内存、而会直接进行数据传输。采用“请求流/响应流”的方式进行传输,可以减少内存占用,降低内存溢出的风险。
    例如:
    // Get method: getResponseBodyAsStream()
    // not use getResponseBody(), or getResponseBodyAsString()
    GetMethod httpGet = new GetMethod(url);  
    InputStream inputStream = httpGet.getResponseBodyAsStream();
    // Post method: getResponseBodyAsStream()
    PostMethod httpPost = new PostMethod(url);  
    InputStream inputStream = httpPost.getResponseBodyAsStream(); 

2)持续握手(Expect-continue handshake)
    在认证系统或其他可能遭到服务器拒绝应答的情况下(如:登陆失败),如果发送整个请求体,则会大大降低效率。此时,可以先发送部分请求(如:只发送请求头)进行试探,如果服务器愿意接收,则继续发送请求体。此项优化主要进行以下配置:
    // use expect-continue handshake
    HttpProtocolParams.setUseExpectContinue(httpParams, true);

3)“旧连接”检查(Stale connection check)
    HttpClient为了提升性能,默认采用了“重用连接”机制,即在有传输数据需求时,会首先检查连接池中是否有可供重用的连接,如果有,则会重用连接。同时,为了确保该“被重用”的连接确实有效,会在重用之前对其进行有效性检查。这个检查大概会花费15-30毫秒。关闭该检查举措,会稍微提升传输速度,但也可能出现“旧连接”过久而被服务器端关闭、从而出现I/O异常。
    关闭旧连接检查的配置为:
    // disable stale check
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

 4)超时设置
    进行超时设置,让连接在超过时间后自动失效,释放占用资源。
    // timeout: get connections from connection pool
    ConnManagerParams.setTimeout(httpParams, 1000);  
    // timeout: connect to the server
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    // timeout: transfer data from server
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
5)连接数限制
    配置每台主机最多连接数和连接池中的最多连接总数,对连接数量进行限制。其中,DEFAULT_HOST_CONNECTIONS和DEFAULT_MAX_CONNECTIONS是由客户端程序员根据需要而设置的。
    // set max connections per host
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_HOST_CONNECTIONS)); 
    // set max total connections
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);


[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.wqry.sm.connection.http;  
  2.   
  3. import java.security.KeyStore;  
  4. import java.util.concurrent.Executors;  
  5. import java.util.concurrent.ThreadPoolExecutor;  
  6.   
  7. import org.apache.http.HttpVersion;  
  8. import org.apache.http.client.HttpClient;  
  9. import org.apache.http.conn.ClientConnectionManager;  
  10. import org.apache.http.conn.params.ConnManagerParams;  
  11. import org.apache.http.conn.scheme.PlainSocketFactory;  
  12. import org.apache.http.conn.scheme.Scheme;  
  13. import org.apache.http.conn.scheme.SchemeRegistry;  
  14. import org.apache.http.conn.ssl.SSLSocketFactory;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  17. import org.apache.http.params.BasicHttpParams;  
  18. import org.apache.http.params.HttpConnectionParams;  
  19. import org.apache.http.params.HttpParams;  
  20. import org.apache.http.params.HttpProtocolParams;  
  21. import org.apache.http.protocol.HTTP;  
  22.   
  23. import android.net.http.AndroidHttpClient;  
  24. import android.util.Log;  
  25.   
  26. import com.wqry.sm.connection.net.EasySSLSocketFactory;  
  27.   
  28. public class HttpConnector {  
  29.   
  30.     private final static int TIMEOUT = 1000;  
  31.     private final static int CONNECT_TIMEOUT = 6000;  
  32.     private final static int SO_TIMEOUT = 10000;  
  33.   
  34.     private static HttpConnector instance = new HttpConnector();  
  35.     private int nThreads = 3;  
  36.     private ThreadPoolExecutor sExecutorService;  
  37.   
  38.     // 服务器秘钥  
  39.     private static KeyStore trustStore;  
  40.   
  41.     public static KeyStore getTrustStore() {  
  42.         return trustStore;  
  43.     }  
  44.   
  45.     public static void setTrustStore(KeyStore trustStore) {  
  46.         HttpConnector.trustStore = trustStore;  
  47.     }  
  48.   
  49.     private HttpClient httpClient;  
  50.     private HttpClient httpsClient;  
  51.   
  52.     private HttpConnector() {  
  53.         sExecutorService = (ThreadPoolExecutor) Executors  
  54.                 .newFixedThreadPool(nThreads);  
  55.     }  
  56.   
  57.     public static HttpConnector getInstance() {  
  58.         return instance;  
  59.     }  
  60.   
  61.     public int getThreadsPoolSize() {  
  62.         return nThreads;  
  63.     }  
  64.   
  65.     public void setThreadsPoolSize(int size) {  
  66.         nThreads = size;  
  67.         sExecutorService.setMaximumPoolSize(nThreads);  
  68.         sExecutorService.setCorePoolSize(nThreads);  
  69.         AndroidHttpClient ahc;  
  70.     }  
  71.   
  72.     public void sendRequest(Runnable runnable) {  
  73.         sExecutorService.execute(runnable);  
  74.     }  
  75.   
  76.     public synchronized HttpClient getHttpClient() {  
  77.         if (null == httpClient) {  
  78.             // 初始化工作  
  79.             HttpParams params = new BasicHttpParams();  
  80.   
  81.             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  82.             HttpProtocolParams.setContentCharset(params,  
  83.                     HTTP.DEFAULT_CONTENT_CHARSET);  
  84.             HttpProtocolParams.setUseExpectContinue(params, true);  
  85.   
  86.             // 设置连接管理器的超时  
  87.             ConnManagerParams.setTimeout(params, TIMEOUT);  
  88.   
  89.             // 设置连接超时  
  90.             HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);  
  91.   
  92.             // 设置Socket超时  
  93.             HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);  
  94.   
  95.             SchemeRegistry schemeRegistry = new SchemeRegistry();  
  96.             schemeRegistry.register(new Scheme("http", PlainSocketFactory  
  97.                     .getSocketFactory(), 80));  
  98.             schemeRegistry.register(new Scheme("https", SSLSocketFactory  
  99.                     .getSocketFactory(), 80));  
  100.   
  101.             ClientConnectionManager connManager = new ThreadSafeClientConnManager(  
  102.                     params, schemeRegistry);  
  103.   
  104.             httpClient = new DefaultHttpClient(connManager, params);  
  105.         }  
  106.   
  107.         return httpClient;  
  108.     }  
  109.   
  110.     public synchronized HttpClient getHttpsClient() {  
  111.         if (null == httpsClient) {  
  112.             // 初始化工作  
  113.             HttpParams params = new BasicHttpParams();  
  114.   
  115.             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  116.             HttpProtocolParams.setContentCharset(params,  
  117.                     HTTP.DEFAULT_CONTENT_CHARSET);  
  118.             HttpProtocolParams.setUseExpectContinue(params, true);  
  119.   
  120.             // 设置连接管理器的超时  
  121.             ConnManagerParams.setTimeout(params, TIMEOUT);  
  122.   
  123.             // 设置连接超时  
  124.             HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);  
  125.   
  126.             // 设置Socket超时  
  127.             HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);  
  128.   
  129.             SchemeRegistry schemeRegistry = new SchemeRegistry();  
  130.   
  131.             schemeRegistry.register(new Scheme("http",  
  132.                     new EasySSLSocketFactory(), 80));  
  133.             try {  
  134.                 schemeRegistry.register(new Scheme("https",  
  135.                         new SSLSocketFactory(trustStore), 443));  
  136.             } catch (Exception e) {  
  137.                 Log.e("HttpRequest""getHttpsClient.register.Exception", e);  
  138.                 schemeRegistry.register(new Scheme("https",  
  139.                         new EasySSLSocketFactory(), 443));  
  140.             }  
  141.             // schemeRegistry.register(new Scheme("http", PlainSocketFactory  
  142.             // .getSocketFactory(), 80));  
  143.             // schemeRegistry.register(new Scheme("https", SSLSocketFactory  
  144.             // .getSocketFactory(), 80));  
  145.   
  146.             ClientConnectionManager connManager = new ThreadSafeClientConnManager(  
  147.                     params, schemeRegistry);  
  148.   
  149.             httpsClient = new DefaultHttpClient(connManager, params);  
  150.         }  
  151.   
  152.         return httpsClient;  
  153.     }  
  154. }  


附录1:关于HttpURLConnection的优化

从Android官网上看到一点,整理如下:

    1)上传数据至服务器时(即:向服务器发送请求),如果知道上传数据的大小,应该显式使用setFixedLengthStreamingMode(int)来设置上传数据的精确值;如果不知道上传数据的大小,则应使用setChunkedStreamingMode(int)——通常使用默认值“0”作为实际参数传入。如果两个函数都未设置,则系统会强制将“请求体”中的所有内容都缓存至内存中(在通过网络进行传输之前),这样会浪费“堆”内存(甚至可能耗尽),并加重隐患。

    2)如果通过流(stream)输入或输出少量数据,则需要使用带缓冲区的流(如BufferedInputStream);大量读取或输出数据时,可忽略缓冲流(不使用缓冲流会增加磁盘I/O,默认的流操作是直接进行磁盘I/O的);

    3)当需要传输(输入或输出)大量数据时,使用“流”来限制内存中的数据量——即:将数据直接放在“流”中,而不是存储在字节数组或字符串中(这些都存储在内存中)。



附录2:Android提供的AndroidHttpClient类

AndroidHttpClient继承自HttpClient,并且使用了ClientConnectionManager进行线程池管理

AndroidHttpClient和DefaultHttpClient的区别: 
AndroidHttpClient不能在主线程中execute,会抛出异常。
AndroidHttpClient通过静态方法newInstance获得实例,参数是代理,不用代理的话填“”。
DefaultHttpClient默认是启用Cookie的,AndroidHttpClient默认不启用Cookie,
要使用的话每次execute时要加一个HttpContext参数,并且添加CookieStore。用完后别忘了close不然不能创建新实例。

源码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /* 
  2.  * Copyright (C) 2007 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package android.net.http;  
  18.   
  19. import com.android.internal.http.HttpDateTime;  
  20. import org.apache.http.Header;  
  21. import org.apache.http.HttpEntity;  
  22. import org.apache.http.HttpEntityEnclosingRequest;  
  23. import org.apache.http.HttpException;  
  24. import org.apache.http.HttpHost;  
  25. import org.apache.http.HttpRequest;  
  26. import org.apache.http.HttpRequestInterceptor;  
  27. import org.apache.http.HttpResponse;  
  28. import org.apache.http.entity.AbstractHttpEntity;  
  29. import org.apache.http.entity.ByteArrayEntity;  
  30. import org.apache.http.client.HttpClient;  
  31. import org.apache.http.client.ResponseHandler;  
  32. import org.apache.http.client.ClientProtocolException;  
  33. import org.apache.http.client.protocol.ClientContext;  
  34. import org.apache.http.client.methods.HttpUriRequest;  
  35. import org.apache.http.client.params.HttpClientParams;  
  36. import org.apache.http.conn.ClientConnectionManager;  
  37. import org.apache.http.conn.scheme.PlainSocketFactory;  
  38. import org.apache.http.conn.scheme.Scheme;  
  39. import org.apache.http.conn.scheme.SchemeRegistry;  
  40. import org.apache.http.impl.client.DefaultHttpClient;  
  41. import org.apache.http.impl.client.RequestWrapper;  
  42. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  43. import org.apache.http.params.BasicHttpParams;  
  44. import org.apache.http.params.HttpConnectionParams;  
  45. import org.apache.http.params.HttpParams;  
  46. import org.apache.http.params.HttpProtocolParams;  
  47. import org.apache.http.protocol.BasicHttpProcessor;  
  48. import org.apache.http.protocol.HttpContext;  
  49. import org.apache.http.protocol.BasicHttpContext;  
  50.   
  51. import java.io.IOException;  
  52. import java.io.InputStream;  
  53. import java.io.ByteArrayOutputStream;  
  54. import java.io.OutputStream;  
  55. import java.util.zip.GZIPInputStream;  
  56. import java.util.zip.GZIPOutputStream;  
  57. import java.net.URI;  
  58.   
  59. import android.content.Context;  
  60. import android.content.ContentResolver;  
  61. import android.net.SSLCertificateSocketFactory;  
  62. import android.net.SSLSessionCache;  
  63. import android.os.Looper;  
  64. import android.util.Base64;  
  65. import android.util.Log;  
  66.   
  67. /** 
  68.  * Implementation of the Apache {@link DefaultHttpClient} that is configured with 
  69.  * reasonable default settings and registered schemes for Android, and 
  70.  * also lets the user add {@link HttpRequestInterceptor} classes. 
  71.  * Don't create this directly, use the {@link #newInstance} factory method. 
  72.  * 
  73.  * <p>This client processes cookies but does not retain them by default. 
  74.  * To retain cookies, simply add a cookie store to the HttpContext:</p> 
  75.  * 
  76.  * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre> 
  77.  */  
  78. public final class AndroidHttpClient implements HttpClient {  
  79.   
  80.     // Gzip of data shorter than this probably won't be worthwhile  
  81.     public static long DEFAULT_SYNC_MIN_GZIP_BYTES = 256;  
  82.   
  83.     // Default connection and socket timeout of 60 seconds.  Tweak to taste.  
  84.     private static final int SOCKET_OPERATION_TIMEOUT = 60 * 1000;  
  85.   
  86.     private static final String TAG = "AndroidHttpClient";  
  87.   
  88.     private static String[] textContentTypes = new String[] {  
  89.             "text/",  
  90.             "application/xml",  
  91.             "application/json"  
  92.     };  
  93.   
  94.     /** Interceptor throws an exception if the executing thread is blocked */  
  95.     private static final HttpRequestInterceptor sThreadCheckInterceptor =  
  96.             new HttpRequestInterceptor() {  
  97.         public void process(HttpRequest request, HttpContext context) {  
  98.             // Prevent the HttpRequest from being sent on the main thread  
  99.             if (Looper.myLooper() != null && Looper.myLooper() == Looper.getMainLooper() ) {  
  100.                 throw new RuntimeException("This thread forbids HTTP requests");  
  101.             }  
  102.         }  
  103.     };  
  104.   
  105.     /** 
  106.      * Create a new HttpClient with reasonable defaults (which you can update). 
  107.      * 
  108.      * @param userAgent to report in your HTTP requests 
  109.      * @param context to use for caching SSL sessions (may be null for no caching) 
  110.      * @return AndroidHttpClient for you to use for all your requests. 
  111.      */  
  112.     public static AndroidHttpClient newInstance(String userAgent, Context context) {  
  113.         HttpParams params = new BasicHttpParams();  
  114.   
  115.         // Turn off stale checking.  Our connections break all the time anyway,  
  116.         // and it's not worth it to pay the penalty of checking every time.  
  117.         HttpConnectionParams.setStaleCheckingEnabled(params, false);  
  118.   
  119.         HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);  
  120.         HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);  
  121.         HttpConnectionParams.setSocketBufferSize(params, 8192);  
  122.   
  123.         // Don't handle redirects -- return them to the caller.  Our code  
  124.         // often wants to re-POST after a redirect, which we must do ourselves.  
  125.         HttpClientParams.setRedirecting(params, false);  
  126.   
  127.         // Use a session cache for SSL sockets  
  128.         SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);  
  129.   
  130.         // Set the specified user agent and register standard protocols.  
  131.         HttpProtocolParams.setUserAgent(params, userAgent);  
  132.         SchemeRegistry schemeRegistry = new SchemeRegistry();  
  133.         schemeRegistry.register(new Scheme("http",  
  134.                 PlainSocketFactory.getSocketFactory(), 80));  
  135.         schemeRegistry.register(new Scheme("https",  
  136.                 SSLCertificateSocketFactory.getHttpSocketFactory(  
  137.                 SOCKET_OPERATION_TIMEOUT, sessionCache), 443));  
  138.   
  139.         ClientConnectionManager manager =  
  140.                 new ThreadSafeClientConnManager(params, schemeRegistry);  
  141.   
  142.         // We use a factory method to modify superclass initialization  
  143.         // parameters without the funny call-a-static-method dance.  
  144.         return new AndroidHttpClient(manager, params);  
  145.     }  
  146.   
  147.     /** 
  148.      * Create a new HttpClient with reasonable defaults (which you can update). 
  149.      * @param userAgent to report in your HTTP requests. 
  150.      * @return AndroidHttpClient for you to use for all your requests. 
  151.      */  
  152.     public static AndroidHttpClient newInstance(String userAgent) {  
  153.         return newInstance(userAgent, null /* session cache */);  
  154.     }  
  155.   
  156.     private final HttpClient delegate;  
  157.   
  158.     private RuntimeException mLeakedException = new IllegalStateException(  
  159.             "AndroidHttpClient created and never closed");  
  160.   
  161.     private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {  
  162.         this.delegate = new DefaultHttpClient(ccm, params) {  
  163.             @Override  
  164.             protected BasicHttpProcessor createHttpProcessor() {  
  165.                 // Add interceptor to prevent making requests from main thread.  
  166.                 BasicHttpProcessor processor = super.createHttpProcessor();  
  167.                 processor.addRequestInterceptor(sThreadCheckInterceptor);  
  168.                 processor.addRequestInterceptor(new CurlLogger());  
  169.   
  170.                 return processor;  
  171.             }  
  172.   
  173.             @Override  
  174.             protected HttpContext createHttpContext() {  
  175.                 // Same as DefaultHttpClient.createHttpContext() minus the  
  176.                 // cookie store.  
  177.                 HttpContext context = new BasicHttpContext();  
  178.                 context.setAttribute(  
  179.                         ClientContext.AUTHSCHEME_REGISTRY,  
  180.                         getAuthSchemes());  
  181.                 context.setAttribute(  
  182.                         ClientContext.COOKIESPEC_REGISTRY,  
  183.                         getCookieSpecs());  
  184.                 context.setAttribute(  
  185.                         ClientContext.CREDS_PROVIDER,  
  186.                         getCredentialsProvider());  
  187.                 return context;  
  188.             }  
  189.         };  
  190.     }  
  191.   
  192.     @Override  
  193.     protected void finalize() throws Throwable {  
  194.         super.finalize();  
  195.         if (mLeakedException != null) {  
  196.             Log.e(TAG, "Leak found", mLeakedException);  
  197.             mLeakedException = null;  
  198.         }  
  199.     }  
  200.   
  201.     /** 
  202.      * Modifies a request to indicate to the server that we would like a 
  203.      * gzipped response.  (Uses the "Accept-Encoding" HTTP header.) 
  204.      * @param request the request to modify 
  205.      * @see #getUngzippedContent 
  206.      */  
  207.     public static void modifyRequestToAcceptGzipResponse(HttpRequest request) {  
  208.         request.addHeader("Accept-Encoding""gzip");  
  209.     }  
  210.   
  211.     /** 
  212.      * Gets the input stream from a response entity.  If the entity is gzipped 
  213.      * then this will get a stream over the uncompressed data. 
  214.      * 
  215.      * @param entity the entity whose content should be read 
  216.      * @return the input stream to read from 
  217.      * @throws IOException 
  218.      */  
  219.     public static InputStream getUngzippedContent(HttpEntity entity)  
  220.             throws IOException {  
  221.         InputStream responseStream = entity.getContent();  
  222.         if (responseStream == nullreturn responseStream;  
  223.         Header header = entity.getContentEncoding();  
  224.         if (header == nullreturn responseStream;  
  225.         String contentEncoding = header.getValue();  
  226.         if (contentEncoding == nullreturn responseStream;  
  227.         if (contentEncoding.contains("gzip")) responseStream  
  228.                 = new GZIPInputStream(responseStream);  
  229.         return responseStream;  
  230.     }  
  231.   
  232.     /** 
  233.      * Release resources associated with this client.  You must call this, 
  234.      * or significant resources (sockets and memory) may be leaked. 
  235.      */  
  236.     public void close() {  
  237.         if (mLeakedException != null) {  
  238.             getConnectionManager().shutdown();  
  239.             mLeakedException = null;  
  240.         }  
  241.     }  
  242.   
  243.     public HttpParams getParams() {  
  244.         return delegate.getParams();  
  245.     }  
  246.   
  247.     public ClientConnectionManager getConnectionManager() {  
  248.         return delegate.getConnectionManager();  
  249.     }  
  250.   
  251.     public HttpResponse execute(HttpUriRequest request) throws IOException {  
  252.         return delegate.execute(request);  
  253.     }  
  254.   
  255.     public HttpResponse execute(HttpUriRequest request, HttpContext context)  
  256.             throws IOException {  
  257.         return delegate.execute(request, context);  
  258.     }  
  259.   
  260.     public HttpResponse execute(HttpHost target, HttpRequest request)  
  261.             throws IOException {  
  262.         return delegate.execute(target, request);  
  263.     }  
  264.   
  265.     public HttpResponse execute(HttpHost target, HttpRequest request,  
  266.             HttpContext context) throws IOException {  
  267.         return delegate.execute(target, request, context);  
  268.     }  
  269.   
  270.     public <T> T execute(HttpUriRequest request,   
  271.             ResponseHandler<? extends T> responseHandler)  
  272.             throws IOException, ClientProtocolException {  
  273.         return delegate.execute(request, responseHandler);  
  274.     }  
  275.   
  276.     public <T> T execute(HttpUriRequest request,  
  277.             ResponseHandler<? extends T> responseHandler, HttpContext context)  
  278.             throws IOException, ClientProtocolException {  
  279.         return delegate.execute(request, responseHandler, context);  
  280.     }  
  281.   
  282.     public <T> T execute(HttpHost target, HttpRequest request,  
  283.             ResponseHandler<? extends T> responseHandler) throws IOException,  
  284.             ClientProtocolException {  
  285.         return delegate.execute(target, request, responseHandler);  
  286.     }  
  287.   
  288.     public <T> T execute(HttpHost target, HttpRequest request,  
  289.             ResponseHandler<? extends T> responseHandler, HttpContext context)  
  290.             throws IOException, ClientProtocolException {  
  291.         return delegate.execute(target, request, responseHandler, context);  
  292.     }  
  293.   
  294.     /** 
  295.      * Compress data to send to server. 
  296.      * Creates a Http Entity holding the gzipped data. 
  297.      * The data will not be compressed if it is too short. 
  298.      * @param data The bytes to compress 
  299.      * @return Entity holding the data 
  300.      */  
  301.     public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)  
  302.             throws IOException {  
  303.         AbstractHttpEntity entity;  
  304.         if (data.length < getMinGzipSize(resolver)) {  
  305.             entity = new ByteArrayEntity(data);  
  306.         } else {  
  307.             ByteArrayOutputStream arr = new ByteArrayOutputStream();  
  308.             OutputStream zipper = new GZIPOutputStream(arr);  
  309.             zipper.write(data);  
  310.             zipper.close();  
  311.             entity = new ByteArrayEntity(arr.toByteArray());  
  312.             entity.setContentEncoding("gzip");  
  313.         }  
  314.         return entity;  
  315.     }  
  316.   
  317.     /** 
  318.      * Retrieves the minimum size for compressing data. 
  319.      * Shorter data will not be compressed. 
  320.      */  
  321.     public static long getMinGzipSize(ContentResolver resolver) {  
  322.         return DEFAULT_SYNC_MIN_GZIP_BYTES;  // For now, this is just a constant.  
  323.     }  
  324.   
  325.     /* cURL logging support. */  
  326.   
  327.     /** 
  328.      * Logging tag and level. 
  329.      */  
  330.     private static class LoggingConfiguration {  
  331.   
  332.         private final String tag;  
  333.         private final int level;  
  334.   
  335.         private LoggingConfiguration(String tag, int level) {  
  336.             this.tag = tag;  
  337.             this.level = level;  
  338.         }  
  339.   
  340.         /** 
  341.          * Returns true if logging is turned on for this configuration. 
  342.          */  
  343.         private boolean isLoggable() {  
  344.             return Log.isLoggable(tag, level);  
  345.         }  
  346.   
  347.         /** 
  348.          * Prints a message using this configuration. 
  349.          */  
  350.         private void println(String message) {  
  351.             Log.println(level, tag, message);  
  352.         }  
  353.     }  
  354.   
  355.     /** cURL logging configuration. */  
  356.     private volatile LoggingConfiguration curlConfiguration;  
  357.   
  358.     /** 
  359.      * Enables cURL request logging for this client. 
  360.      * 
  361.      * @param name to log messages with 
  362.      * @param level at which to log messages (see {@link android.util.Log}) 
  363.      */  
  364.     public void enableCurlLogging(String name, int level) {  
  365.         if (name == null) {  
  366.             throw new NullPointerException("name");  
  367.         }  
  368.         if (level < Log.VERBOSE || level > Log.ASSERT) {  
  369.             throw new IllegalArgumentException("Level is out of range ["  
  370.                 + Log.VERBOSE + ".." + Log.ASSERT + "]");  
  371.         }  
  372.   
  373.         curlConfiguration = new LoggingConfiguration(name, level);  
  374.     }  
  375.   
  376.     /** 
  377.      * Disables cURL logging for this client. 
  378.      */  
  379.     public void disableCurlLogging() {  
  380.         curlConfiguration = null;  
  381.     }  
  382.   
  383.     /** 
  384.      * Logs cURL commands equivalent to requests. 
  385.      */  
  386.     private class CurlLogger implements HttpRequestInterceptor {  
  387.         public void process(HttpRequest request, HttpContext context)  
  388.                 throws HttpException, IOException {  
  389.             LoggingConfiguration configuration = curlConfiguration;  
  390.             if (configuration != null  
  391.                     && configuration.isLoggable()  
  392.                     && request instanceof HttpUriRequest) {  
  393.                 // Never print auth token -- we used to check ro.secure=0 to  
  394.                 // enable that, but can't do that in unbundled code.  
  395.                 configuration.println(toCurl((HttpUriRequest) request, false));  
  396.             }  
  397.         }  
  398.     }  
  399.   
  400.     /** 
  401.      * Generates a cURL command equivalent to the given request. 
  402.      */  
  403.     private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {  
  404.         StringBuilder builder = new StringBuilder();  
  405.   
  406.         builder.append("curl ");  
  407.   
  408.         for (Header header: request.getAllHeaders()) {  
  409.             if (!logAuthToken  
  410.                     && (header.getName().equals("Authorization") ||  
  411.                         header.getName().equals("Cookie"))) {  
  412.                 continue;  
  413.             }  
  414.             builder.append("--header \"");  
  415.             builder.append(header.toString().trim());  
  416.             builder.append("\" ");  
  417.         }  
  418.   
  419.         URI uri = request.getURI();  
  420.   
  421.         // If this is a wrapped request, use the URI from the original  
  422.         // request instead. getURI() on the wrapper seems to return a  
  423.         // relative URI. We want an absolute URI.  
  424.         if (request instanceof RequestWrapper) {  
  425.             HttpRequest original = ((RequestWrapper) request).getOriginal();  
  426.             if (original instanceof HttpUriRequest) {  
  427.                 uri = ((HttpUriRequest) original).getURI();  
  428.             }  
  429.         }  
  430.   
  431.         builder.append("\"");  
  432.         builder.append(uri);  
  433.         builder.append("\"");  
  434.   
  435.         if (request instanceof HttpEntityEnclosingRequest) {  
  436.             HttpEntityEnclosingRequest entityRequest =  
  437.                     (HttpEntityEnclosingRequest) request;  
  438.             HttpEntity entity = entityRequest.getEntity();  
  439.             if (entity != null && entity.isRepeatable()) {  
  440.                 if (entity.getContentLength() < 1024) {  
  441.                     ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  442.                     entity.writeTo(stream);  
  443.   
  444.                     if (isBinaryContent(request)) {  
  445.                         String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);  
  446.                         builder.insert(0"echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");  
  447.                         builder.append(" --data-binary @/tmp/$$.bin");  
  448.                     } else {  
  449.                         String entityString = stream.toString();  
  450.                         builder.append(" --data-ascii \"")  
  451.                                 .append(entityString)  
  452.                                 .append("\"");  
  453.                     }  
  454.                 } else {  
  455.                     builder.append(" [TOO MUCH DATA TO INCLUDE]");  
  456.                 }  
  457.             }  
  458.         }  
  459.   
  460.         return builder.toString();  
  461.     }  
  462.   
  463.     private static boolean isBinaryContent(HttpUriRequest request) {  
  464.         Header[] headers;  
  465.         headers = request.getHeaders(Headers.CONTENT_ENCODING);  
  466.         if (headers != null) {  
  467.             for (Header header : headers) {  
  468.                 if ("gzip".equalsIgnoreCase(header.getValue())) {  
  469.                     return true;  
  470.                 }  
  471.             }  
  472.         }  
  473.   
  474.         headers = request.getHeaders(Headers.CONTENT_TYPE);  
  475.         if (headers != null) {  
  476.             for (Header header : headers) {  
  477.                 for (String contentType : textContentTypes) {  
  478.                     if (header.getValue().startsWith(contentType)) {  
  479.                         return false;  
  480.                     }  
  481.                 }  
  482.             }  
  483.         }  
  484.         return true;  
  485.     }  
  486.   
  487.     /** 
  488.      * Returns the date of the given HTTP date string. This method can identify 
  489.      * and parse the date formats emitted by common HTTP servers, such as 
  490.      * <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a>, 
  491.      * <a href="http://www.ietf.org/rfc/rfc0850.txt">RFC 850</a>, 
  492.      * <a href="http://www.ietf.org/rfc/rfc1036.txt">RFC 1036</a>, 
  493.      * <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC 1123</a> and 
  494.      * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/asctime.html">ANSI 
  495.      * C's asctime()</a>. 
  496.      * 
  497.      * @return the number of milliseconds since Jan. 1, 1970, midnight GMT. 
  498.      * @throws IllegalArgumentException if {@code dateString} is not a date or 
  499.      *     of an unsupported format. 
  500.      */  
  501.     public static long parseDate(String dateString) {  
  502.         return HttpDateTime.parse(dateString);  
  503.     }  
  504. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值