如何在android中实现请求超时?

时间:2010-07-09 13:02:02

标签: android

朋友,

当我尝试调用webservice并且服务器/互联网不可用时,我遇到了问题。看来, 连接需要很长时间才能超时

我可以手动设置timout以向用户显示错误消息吗?

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:4)

您可以尝试这样做:

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
}

答案 1 :(得分:4)

有两种超时:

  1. 连接超时
  2. 这是建立连接的时间

    1. 套接字超时
    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
          }
      

答案 2 :(得分:1)

以这种方式设置您的HttpClient。

    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, connectionTimeoutInMs);
    httpClient = new DefaultHttpClient(httpParams);

答案 3 :(得分:0)

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...");
}