为什么android HttpURLConnection不遵守超时值?

And*_*ázi 15 android timeout httpurlconnection

我有以下代码块:

try {
    URL url = new URL("http://site-to-test.com/nonexistingpage.html");

    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setRequestProperty("User-Agent", CoreProtocolPNames.USER_AGENT);
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(500); // timeout is in milliseconds
    urlc.connect();

    if (urlc.getResponseCode() == 404) {
        // Server was reachable
        Log.i(TAG, "Server is reachable");
    }

} catch (MalformedURLException mue) {
    Log.e(TAG, "MalformedURLException: " + mue.getMessage());
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

site-to-test通过当前网络无法访问域时,此代码会在接收之前阻塞大约30-40秒IOException.我特意将超时值设置为500毫秒.我在这里错过了什么?无论网络状态和网站的可用性如何,上述块都不应该在半秒内终止?

And*_*ázi 13

似乎Java URLConnection在读取时没有提供故障安全超时

正如文章所解释的那样,解决方案是使用单独的Thread进行计时,并在完成计时器线程后手动断开HttpURLConnection.