HttpURLConnection setConnectTimeout()无效

Jon*_*now 41 java android

我正在使用HTTPUrlConnection连接到一个简单的RSS提要.它完美地运作.我想在连接中添加超时,因为我不希望我的应用程序在连接错误或其他情况下挂起.这是我使用的代码,setConnectTimeout方法没有任何效果.

        HttpURLConnection http = (HttpURLConnection) mURL.openConnection();
        http.setConnectTimeout(15000); //timeout after 15 seconds
...
Run Code Online (Sandbox Code Playgroud)

如果它有助于我在android上开发.

pap*_*pap 60

您应该尝试设置读取超时(http.setReadTimeout()).通常情况下,Web服务器会很乐意接受您的连接,但实际响应请求可能会很慢.

  • 如果连接到路由器但互联网连接断开,对我不起作用. (3认同)

Can*_*ner 18

您可能要么/两个:
1)不要从连接
2中读取任何内容.不要正确捕获和处理异常

如前所述这里,使用类似的逻辑是:

int TIMEOUT_VALUE = 1000;
try {
    URL testUrl = new URL("http://google.com");
    StringBuilder answer = new StringBuilder(100000);

    long start = System.nanoTime();

    URLConnection testConnection = testUrl.openConnection();
    testConnection.setConnectTimeout(TIMEOUT_VALUE);
    testConnection.setReadTimeout(TIMEOUT_VALUE);
    BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        answer.append(inputLine);
        answer.append("\n");
    }
    in.close();

    long elapsed = System.nanoTime() - start;
    System.out.println("Elapsed (ms): " + elapsed / 1000000);
    System.out.println("Answer:");
    System.out.println(answer);
} catch (SocketTimeoutException e) {
    System.out.println("More than " + TIMEOUT_VALUE + " elapsed.");
}
Run Code Online (Sandbox Code Playgroud)


NoB*_*ugs 7

我遇到了类似的问题 - 因为HttpUrlConnection不会在下载过程中超时.例如,如果您在下载时关闭wifi,我的继续说它正在下载,卡在相同的百分比.

我找到了一个使用TimerTask连接到名为DownloaderTask的AsyncTask的解决方案.尝试:

class Timeout extends TimerTask {
    private DownloaderTask _task;

    public Timeout(DownloaderTask task) {
        _task = task;
    }

    @Override
    public void run() {
        Log.w(TAG,"Timed out while downloading.");
        _task.cancel(false);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后在实际的下载循环中设置一个超时错误的计时器:

                    _outFile.createNewFile();
                    FileOutputStream file = new FileOutputStream(_outFile);
                    out = new BufferedOutputStream(file);
                    byte[] data = new byte[1024];
                    int count;
                    _timer = new Timer();
                    // Read in chunks, much more efficient than byte by byte, lower cpu usage.
                    while((count = in.read(data, 0, 1024)) != -1 && !isCancelled()) { 
                        out.write(data,0,count);
                        downloaded+=count;
                        publishProgress((int) ((downloaded/ (float)contentLength)*100));
                        _timer.cancel();
                        _timer = new Timer();
                        _timer.schedule(new Timeout(this), 1000*20);
                    }
                    _timer.cancel();
                    out.flush();
Run Code Online (Sandbox Code Playgroud)

如果它超时,并且在20秒内不会下载1K,它取消而不是看起来永远下载.


Soj*_*P R 6

我面临着同样的问题。设置connectionTimeoutandreadTimeout似乎没有像预期的那样返回异常,但是真的。我花了一段时间来检查URLConnection()方法并了解发生了什么。在文档中setConnectTimeout有一个警告

“如果主机名解析为多个 IP 地址,该客户端将尝试每个地址。​​如果连接到这些地址中的每一个都失败,则在连接尝试引发异常之前将经过多次超时。” 这意味着如果您的主机解析了 10 个 ip,您的实际超时将是“10*readTimeoutSet”。

您可以在此处检查主机名的 ips