为什么超时值是不尊重搭载Android HttpURLConnection的? [英] Why timeout value is not respected by android HttpURLConnection?

查看:302
本文介绍了为什么超时值是不尊重搭载Android 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());
}

站点到测试域名无法访问,通过目前的网络,接收<$ C之前约30-40秒这code块$ C> 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.

这篇关于为什么超时值是不尊重搭载Android HttpURLConnection的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆