没有抛出超时异常

时间:2014-04-11 06:19:10

标签: android http exception timeoutexception

有人可以帮助我,为什么这段代码不会超时。

httpParams = new BasicHttpParams();
    int some_reasonable_timeout = (int) (10 * DateUtils.SECOND_IN_MILLIS);
    HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
    HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);

    try {
    response = client.execute(request);
    }
    catch(Exception e) {   //catching timeout exception
        response = null;
    }
    return response;

我将计算机与互联网断开连接,然后从android device发出请求。但它不会抛出time out exception。当超时异常抛出时,我可能没有得到。我想这样做,当系统在10秒内没有响应时退出request。请帮我解决这个问题。


已更新

试试这个

    //      httpParams = new BasicHttpParams();
//      int some_reasonable_timeout = (int) (10 * DateUtils.SECOND_IN_MILLIS);
//      HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
//      HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
//      request.setParams(httpParams);

    setTimeouts(request.getParams());

    try {
    response = client.execute(request);
    }
    catch(Exception e) {   //catching timeout exception
        response = null;
        return response;
    }
    return response;

1 个答案:

答案 0 :(得分:1)

似乎HttpConnectionParams.setSoTimeout()not working well。我不确定这是否符合您的要求,但对我有用:

private static final int CONNECTION_TIMEOUT = 5000; // Timeout until a connection is established
private static final int SOCKET_TIMEOUT = 5000; // Timeout for waiting for data
private static final long MCC_TIMEOUT = 5000;

HttpGet httpGet = new HttpGet(url);
setTimeouts(httpGet.getParams());

private static void setTimeouts(HttpParams params) {
  params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
  params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
  params.setLongParameter(ConnManagerPNames.TIMEOUT, MCC_TIMEOUT);
}
相关问题