【问题标题】:Time out exception not thrown未抛出超时异常
【发布时间】:2014-04-11 06:19:10
【问题描述】:

谁能帮我解释一下为什么这段代码不会抛出超时异常。

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;

【问题讨论】:

  • 投反对票的人请说明你投反对票的原因。有什么问题。

标签: android http exception timeoutexception


【解决方案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);
}

【讨论】:

  • 你说的无法是什么意思?您是否尝试过并且仍然发生相同的情况?
  • 它不起作用。设备仍在继续发出请求。
  • 它对我有用,可能不是精确的 5 秒超时,而是近似值。你确定要调用setTimeouts() 方法吗?
  • 我猜你还在代码中添加了setTimeouts(...) 实现,尽管你的问题中没有包含它,对吧?
猜你喜欢
  • 2016-09-16
  • 2011-04-11
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多