(1)采用单例模式(重用HttpClient实例)
    对于一个通信单元甚至是整个应用程序,Apache强烈推荐只使用一个HttpClient的实例。例如:

private static HttpClient httpClient = null;
 
    private static synchronized HttpClient getHttpClient() {
       if(httpClient == null) {
           final HttpParams httpParams = new BasicHttpParams();  
           httpClient = new DefaultHttpClient(httpParams); 
       }  
  
      return httpClient;
    }

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

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

  • // timeout: connect to the server
  • HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
  • // timeout: transfer data from server
  • HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
  • // set max connections per host
  • ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_HOST_CONNECTIONS));
  • // set max total connections
  • ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
  • // use expect-continue handshake
  • HttpProtocolParams.setUseExpectContinue(httpParams, true);
  • // disable stale check
  • HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
  • HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
  • HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
  • HttpClientParams.setRedirecting(httpParams, false);
  • // set user agent
  • String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
  • HttpProtocolParams.setUserAgent(httpParams, userAgent);
  • // disable Nagle algorithm
  • HttpConnectionParams.setTcpNoDelay(httpParams, true);
  • HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
  • // scheme: http and https
  • SchemeRegistry schemeRegistry = new SchemeRegistry();
  • schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  • schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
  • ClientConnectionManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
  • httpClient = new DefaultHttpClient(manager, httpParams);
  • }
  • return httpClient;
  • }