1

所以我遇到了一个不工作的套接字超时。我遵循了现有帖子给出的所有说明,但它仍然无法正常工作(我从未收到套接字超时异常)。这是我的代码:

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);
}
4

3 回答 3

2

不久前,我遇到了类似的问题。我做了一些实验,发现当我在模拟器中运行我的应用程序时,超时不起作用,而当我在真实设备上运行它时,它确实起作用了。我用DefaultHttpClient,HttpUrlConnection和对其进行了测试AndroidHttpClient,所有三个都显示了相同的结果;在模拟器中大约 20 秒后出现 IOexception (UnknownHostException),无论设置的超时如何。

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

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

于 2012-05-30T08:19:15.903 回答
0

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

问题可能出在 Apache HTTP 客户端中。请参阅 HTTPCLIENT-1098。在 4.1.2 中修复。

超时异常尝试反转 DNS IP,以进行日志记录。这需要额外的时间才能真正触发异常。

于 2013-11-17T13:23:50.010 回答
0

在我的示例中,设置了两个超时。连接超时抛出“java.net.SocketTimeoutException: Socket is not connected”和套接字超时“java.net.SocketTimeoutException: The operation timed out”。

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);

于 2012-05-25T07:04:51.353 回答