Android 上的 Http 连接超时不起作用 [英] Http connection timeout on Android not working

查看:40
本文介绍了Android 上的 Http 连接超时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个连接到网络服务的应用程序,如果无法连接,我不希望它等待太久.因此,我设置了 httpparams 的 connectionTimeout.不过好像没什么效果.

I'm writing an application that connects to a webservice and I don't want it to wait too long if it can't get a connection. I therefore set the connectionTimeout of the httpparams. But it doesn't seem to have any effect whatsoever.

为了测试,我暂时关闭了 WLAN.应用程序尝试连接相当长的一段时间(超过我想要的 3 秒),然后抛出 UnknownHostException.

To test I turn of my WLAN temporarily. The application tries to connect for quite some time (way more than the 3 seconds I want) and then throws an UnknownHostException.

这是我的代码:

try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 3000);
    HttpConnectionParams.setSoTimeout(params, 3000);

    httppost = new HttpPost(URL);
    StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
    httppost.setEntity(se);
    //Code stops here until UnknownHostException is thrown.
    BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);

    HttpEntity entity = httpResponse.getEntity();
    return entity;

}catch (Exception e){
    e.printStackTrace();
}

有人知道我错过了什么吗?

Anyone have any ideas what I missed?

推荐答案

尝试这样做:

HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
httpPost.setEntity(se);

HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse)  httpClient.execute(httpPost);

HttpEntity entity = httpResponse.getEntity();
return entity;

然后您可以捕获可能的ConnectTimeoutException.

You then can catch a possible ConnectTimeoutException.

这篇关于Android 上的 Http 连接超时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆