httpclient4.2.1最新版连接池配置

	/**
	 * 适合多线程的HttpClient,用httpClient4.2.1实现
	 * @return DefaultHttpClient
	 */
	public static DefaultHttpClient getHttpClient()
	{  		
	    // 设置组件参数, HTTP协议的版本,1.1/1.0/0.9 
		HttpParams params = new BasicHttpParams(); 
	    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
	    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); 
	    HttpProtocolParams.setUseExpectContinue(params, true); 	  

	    //设置连接超时时间 
	    int REQUEST_TIMEOUT = 10*1000;	//设置请求超时10秒钟 
		int SO_TIMEOUT = 10*1000; 		//设置等待数据超时时间10秒钟 
		//HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
		//HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
	    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);  
	    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT); 
	  
		//设置访问协议 
		SchemeRegistry schreg = new SchemeRegistry();  
		schreg.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory())); 
		schreg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); 	  
		
		//多连接的线程安全的管理器 
		PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schreg);
		pccm.setDefaultMaxPerRoute(20);	//每个主机的最大并行链接数 
		pccm.setMaxTotal(100);			//客户端总并行链接最大数    
		
		DefaultHttpClient httpClient = new DefaultHttpClient(pccm, params);  
		return httpClient;
	}

如果以上代码有问题可能是现在安卓包里缺少PoolingClientConnectionManager这个类,倒入httpclient4.2.1解决问题。

 

另一种直接使用安卓内置的httpclient包的用法(ClientConnectionManager线程安全的连接管理类):

/**
	 * 
	 * @return DefaultHttpClient
	 */
	public static synchronized DefaultHttpClient getHttpClient()
	{  		
		if(httpClient == null)
		{					
			Log.v(TAG, "->> httpClient is null ->> do getHttpClient");
		    // 设置组件参数, HTTP协议的版本,1.1/1.0/0.9 
			HttpParams params = new BasicHttpParams(); 
		    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
		    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); 
		    HttpProtocolParams.setUseExpectContinue(params, true); 	  
	
		    //设置连接超时时间 
		    int REQUEST_TIMEOUT = 10 * 1000;	//设置请求超时10秒钟 
			int SO_TIMEOUT = 10 * 1000; 		//设置等待数据超时时间10秒钟 
			HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
            ConnManagerParams.setTimeout(params, 1000); //从连接池中取连接的超时时间
       		  
			//设置访问协议 
			SchemeRegistry schreg = new SchemeRegistry();  
			schreg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
			schreg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); 	
						
			// 使用线程安全的连接管理来创建HttpClient  
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schreg);  
			httpClient = new DefaultHttpClient(conMgr, params); 
		}
		return httpClient;
	}


 

你可能感兴趣的:(Android)