HttpURLConnection setConnectTimeout() 没有效果

2022-09-01 01:53:47

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

        HttpURLConnection http = (HttpURLConnection) mURL.openConnection();
        http.setConnectTimeout(15000); //timeout after 15 seconds
...

如果它有帮助,我正在Android上开发。


答案 1

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


答案 2

您可能两者兼而有之:
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.");
}

推荐