Android - setSoTimeout无效

时间:2012-05-25 06:54:15

标签: android android-asynctask httpconnection socket-timeout-exception

所以我遇到了一个无效的套接字超时。我遵循现有帖子给出的所有指令,但它仍然无效(我从未得到套接字超时异常)。这是我的代码:

AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
   @Override
   protected String doInBackground(String... params) {
      String location = params[0];

      try {
         HttpGet httpGet = new HttpGet(location);
         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 = 0;
         HttpConnectionParams.setConnectionTimeout(httpParameters,
               timeoutConnection);

         // Set the default socket timeout (SO_TIMEOUT)
         // in milliseconds which is the timeout for waiting for data.
         int timeoutSocket = 2000;
         HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

         DefaultHttpClient client = new DefaultHttpClient(httpParameters);
         Log.d(this.getClass().getSimpleName(), "STARTING CLIENT!!! ");
         HttpResponse response = client.execute(httpGet);
         Log.d(this.getClass().getSimpleName(), "CLIENT CANCELLED!!! ");

         if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            return new Scanner(out.toString()).useDelimiter("\\A").next();
         } else {
            return "";
         }
      } catch (IOException e) {
         e.printStackTrace();
         return null;
      } catch (URISyntaxException e) {
         e.printStackTrace();
         return null;
      }
   }

   @Override
   protected void onPostExecute(String result) {
      try {
         // doStuff
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
};
task.execute(location);

所以我应该在两秒后得到套接字超时异常,但客户端只是忽略它。有什么帮助吗?

提前致谢


所以这里是所有代码:

public void fetch(String location) {    
    AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            String location = params[0];

            try {
                HttpGet httpGet = new HttpGet(location);
                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 = 0;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 2000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                DefaultHttpClient client = new DefaultHttpClient(httpParameters);
                Log.d(this.getClass().getSimpleName(), "STARTING CLIENT!!! ");
                HttpResponse response = client.execute(httpGet);
                Log.d(this.getClass().getSimpleName(), "CLIENT CANCELLED!!! ");

                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    return new Scanner(out.toString()).useDelimiter("\\A").next();
                } else {
                    return "";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (URISyntaxException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                //doStuff
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    task.execute(location);
}

3 个答案:

答案 0 :(得分:2)

前段时间我遇到了类似的问题。我已经进行了一些实验,并注意到当我在模拟器中运行我的应用程序时,超时不起作用,当我在真实设备上运行它时它确实有效。我使用DefaultHttpClientHttpUrlConnectionAndroidHttpClient对其进行了测试,所有三个都显示了相同的结果;无论任何设置超时,模拟器中大约20秒后的IOexception(UnknownHostException)。

谷歌搜索显示,其他人也报告了超时问题:

所提议的解决方案都不适合我,所以我想唯一可靠的解决方案就是自己管理超时。

答案 1 :(得分:0)

在我的示例中,设置了两个超时。连接超时抛出“java.net.SocketTimeoutException:Socket未连接”和套接字超时“java.net.SocketTimeoutException:操作超时”。

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 = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

如果要设置任何现有HTTPClient的参数(例如DefaultHttpClient或AndroidHttpClient),可以使用函数setParams()。

httpClient.setParams(httpParameters);

答案 2 :(得分:0)

请参阅:https://stackoverflow.com/a/20031077/2609238

问题可能出在Apache HTTP Client中。请参阅HTTPCLIENT-1098。已在4.1.2中修复。

超时异常会尝试将DNS反转为IP,以便进行日志记录。这需要额外的时间,直到实际触发异常。