Android http超时选项的测试

Android http超时选项的测试

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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值