如何在android中实现请求超时?
Posted
技术标签:
【中文标题】如何在android中实现请求超时?【英文标题】:how to implement request timeout in android? 【发布时间】:2011-03-13 20:54:07 【问题描述】:朋友们,
当我尝试调用 web 服务并且服务器/互联网不可用时,我遇到了问题。看来, 连接需要很长时间才能超时
我可以手动设置 timout 以向用户显示错误消息吗?
任何帮助将不胜感激。
【问题讨论】:
【参考方案1】:你可以尝试这样做:
URL url;
URLConnection connection;
try
url = new URL("http://foo.bar.com");
connection = url.openConnection();
connection.setConnectTimeout(3000); // set 3 seconds for timeout
connection.connect();
catch(SocketTimeoutException ss)
// show message to the user
【讨论】:
【参考方案2】:有两种超时:
-
连接超时
这是建立连接之前的时间
-
套接字超时
即等待接收数据的超时时间,任意设置为0表示无限超时,两者均为默认值,设置一个不影响另一个。
try
BasicHttpParams httpParams = new BasicHttpParams();
//this will set socket timeout
HttpConnectionParams.setSoTimeout(httpParams, /*say*/ 3000);
//this will set connection timeout
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
client = new DefaultHttpClient(httpParams);
String url = "some-url";
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
//here use the received response
catch(ConnectTimeoutException ex)
//handle connection timeout here
catch(SocketTimeoutException ex)
//handle socket timeout here
【讨论】:
【参考方案3】:以这种方式设置您的 HttpClient。
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, connectionTimeoutInMs);
httpClient = new DefaultHttpClient(httpParams);
【讨论】:
这对我有用,但它没有抛出异常,此外,状态解析为 200 OK。【参考方案4】:This will work always...
try
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, Constants.CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, Constants.SOCKET_CONN_TIMEOUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
url = "write-your-web-url-here";
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity`enter code here`();
if(entity != null) is = entity.getContent();
catch(ConnectTimeoutException timeoutException)
System.out.println("ConnectTimeoutException Occured...");
catch(SocketTimeoutException socketTimeoutException)
System.out.println("SocketTimeoutException Occured...")
catch(Exception e)
System.out.println("Exception Occured...");
【讨论】:
以上是关于如何在android中实现请求超时?的主要内容,如果未能解决你的问题,请参考以下文章