/**
* Create a thread-safe client. This client does not do redirecting, to allow us to capture
* correct "error" codes.
*
* @return HttpClient
*/
public static final DefaultHttpClient createHttpClient() {
// Sets up the http part of the service. SchemeRegistry类被用来维护一个Schemes的集合
final SchemeRegistry supportedSchemes = new SchemeRegistry();
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
//初始化连接套接字,HttpClient用户在应用程序运行时提供特定的套接字初始化代码。
// 套接字是IP 地址和相应 TCP/UDP 端口号的组合体
final SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
//self added ---设置HttpClient支持HTTP和HTTPS两种模式
supportedSchemes.register(new Scheme("https", sf, 443));
//self added ---
// Set some client http client parameter defaults.
final HttpParams httpParams = createHttpParams();
HttpClientParams.setRedirecting(httpParams, false);
// 使用线程安全的连接管理来创建HttpClient
/*
* ThreadSafeClientConnManager 是一个很复杂的实现,它管理一个客户连接池,服务多个执行线程的连接请求,连接被每个路由放入池中。
* 连接池中可用的已经存在持久连接的路由请求由池中租借的连接进行服务,而不是创建一个新的连接分支。
* ThreadSafeClientConnManager在每个路由中维持一个最大的连接限制。缺省的应用对每个路由创建仅仅2个concurrent连接,总数不超过20个 连接。
对于很多现实的应用,这些限制可能出现太多的限制, 特别是如果他们使用HTTP作为一个 传输协议进行服务。连接限制.然而,可以通过HTTP参数进行调整。
// Increase max total connection to 200
ConnManagerParams.setMaxTotalConnections(params, 200);
// Increase default max connection per route to 20
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
*/
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams,
supportedSchemes);
return new DefaultHttpClient(ccm, httpParams);
}
/**
* Create the default HTTP protocol parameters.
*/
private static final HttpParams createHttpParams() {
//HttpParams接口代表一个不可改变值的集合,定义一个组件运行时行为。
final HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
//self added --- 设置一些基本参数 HTTP请求执行参数
HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
paramsBean.setVersion(HttpVersion.HTTP_1_1);// 定义使用HTTP协议版本, 如果不设置此参数将使用HTTP/1.1
paramsBean.setContentCharset(HTTP.UTF_8);//定义字符集用于每个内容体的默认编码 ,如果不设置此参数将使用ISO-8859-1
ConnManagerParams.setTimeout(params, 1000); /* 从连接池中取连接的超时时间 */
//self added ---
//连接管理
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);//建立连接的超时时间(以毫秒为单位)当值为0被解释成一个无限超时,如果此参数不设置,连接操作不会超时(无限超时)。
HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); //以毫秒为单位定义套接字超时(SO_TIMEOUT)。当值为0被解释成一个无限的暂停,如果此参数不设置,读操作不会超时(无限暂停)。
HttpConnectionParams.setSocketBufferSize(params, 8192);//接收/传输HTTP消息时,确定socket内部缓冲区缓存数据的大小,如果此参数不设置,HttpClient将分配8192字节scoket缓冲区
return params;
}