Android通過HttpConnectionParams類為http參數設置提供了兩個超時的設置選項,分別是setSoTimeout和setConnectionTimeout。初看一眼Android官方給的文檔對這個兩個方法的具體含義有一種不理解不夠清楚的感覺,所以決定通過測試的方式來看看到底在什麼情況下這兩個參數會起作用。
經過測試可以發現,setConnectionTimeout設置了建立連接的超時,這是針對TCP的三次握手而言的,如果在指定時間內無法和http服務器建立TCP連接,就會拋出ConnectionTimeoutException。setSoTimeout則設置的是TCP保活時間,在建立了連接之後的指定時間內沒有收到服務器發來的相應的數據包,則拋出SocketTimeoutException.
一、測試代碼
復制代碼
private String urlString;
private int timeout1,timeout2;
MyAsyncTask(String url,int timeout1,int timeout2){
urlString=url;
this.timeout1=timeout1;
this.timeout2=timeout2;
}
@Override
protected String doInBackground(String... params) {
httpget(urlString,timeout1,timeout2);
return "test";
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncTask("http://www.xiaonei.com:1234",3000,5000).execute("start");
new MyAsyncTask("http://www.baidu.com",3000,5000).execute("start");
}
private void httpget(String Url,int timeout1,int timeout2) {
Log.v("httpget", "httpget start timeout1 is "+timeout1+"timeout2 is "+timeout2);
int timeoutConnection = timeout1; // until connection is established
int timeoutSocket = timeout2; // timeout for waiting for data
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet postRequest = new HttpGet(Url);
HttpResponse httpResp = null;
try {
httpResp = httpClient.execute(postRequest);
} catch (ClientProtocolException e) {
Log.v("Main", "clinet protocol exception");
return;
}catch (SocketTimeoutException e) {
// TODO: handle exception
Log.v("Main", "socket timeout"+timeout2);
return;
}catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.v("Main", "connection timeout"+timeout1);
return;
}
catch (IOException e) {
Log.v("Main", "io exception");
return;
}
}