我有以下代碼塊:爲什麼超時值不被android 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());
}
當site-to-test
域不是通過當前的網絡可到達的,在接收到前IOException
約30-40秒這個代碼塊。我特別將超時值設置爲500ms。我在這裏錯過了什麼?不管網絡狀態和網站的可用性如何,上述塊不應該在半秒內終止?
可以使用的TimerTask和樣本使用這個類定時器一起設置限制.... –
順便說一句,你正在做一個單獨的'Thread'(或'AsyncTask'),對吧? –
是的,亞歷克斯,我不會夢想阻止UI線程。 –