在httprequest android中设置超时 [英] set timeout in httprequest android
本文介绍了在httprequest android中设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码通过http请求从服务器获取数据.
I am using the following code to get data from the server with http request.
HttpClient client = new DefaultHttpClient();
String URL = urlGenerator();
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
...
}
它工作正常.但是,如果手机连接到wifi或gprs 3g,但互联网无法正常工作或互联网连接不存在,我想使用以上代码中的超时功能.
Its working fine.But in case if the phone is connected to wifi or gprs 3g but internet is not working or internet connection is not there, i want to use the timeout feature in the above code.
说3秒后,我想显示超时,请重试. 我怎么做. 如果超时,我想在textviw连接超时中显示文本..我该怎么做 请帮助
say after 3 sec i want to show timeout please try again.. how do i do that. in case of time out i want to show a text in the textviw connection timeout .. how do i do that please help
推荐答案
您可以执行以下操作:
try{
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 6000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
} catch (ConnectTimeoutException e) {
//Here Connection TimeOut excepion
Toast.makeText(xyz.this, "Your connection timedout", 10000).show();
}
这篇关于在httprequest android中设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文