为什么超时值是不尊重搭载Android HttpURLConnection的?Android、HttpURLConnection

由网友(清风烈酒)分享简介:我有以下的code座:I have the following code block:try {URL url = new URL("http://site-to-test.com/nonexistingpage.html");HttpURLConnection urlc = (HttpURLConnection)...

我有以下的code座:

I have the following code block:

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());
}

站点到测试域名无法访问,通过目前的网络,接收 IOException异常。我专门超时值设置为500毫秒。我在想什么吗?如果不是以上块半秒终止的网络状态和站点的可用性,不管?

When the site-to-test domain is not reachable through the current network, this code blocks for about 30-40 seconds before receiving the IOException. And I specifically set the timeout value to 500ms. What am I missing here? Shouldn't the above block terminate in half a second, regardless of the network state and the site's availability?

推荐答案

看来的的Java URLConnection的没有提供自动防故障超时读取

解决的办法是,作为文章的介绍,使用一个单独的线程用于计时,并手动断开HttpURLConnection的一次计时器线程完成。

The solution is, as the article explains, to use a separate Thread for timing, and disconnect the HttpURLConnection manually once the timer thread is done.

阅读全文

相关推荐

最新文章