/**
* 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;
}