如何在Java中为Android设置HttpResponse超时

问题:

我已经创建了以下检查连接状态的功能:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpClient();

    try {
      String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
                   + strSessionString + "/ConnectionStatus";
      Log.d("phobos", "performing get " + url);
      HttpGet method = new HttpGet(new URI(url));
      HttpResponse response = httpClient.execute(method);

      if (response != null) {
        String result = getResponse(response.getEntity());
        ...

当我关闭服务器进行测试时,执行时间会很长一段时间

HttpResponse response = httpClient.execute(method);

有人知道如何设置超时以避免等待太久?
谢谢!

回答:

在我的例子中,设置了两个超时。连接超时引发“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);

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to set HttpResponse timeout for Android in Java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

3 + 5 =