我有以下代码块:
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
通过当前网络无法访问域时,此代码会阻塞大约 30-40 秒,然后才会收到IOException
. 我特意将超时值设置为 500ms。我在这里想念什么?无论网络状态和站点的可用性如何,上述块不应该在半秒内终止吗?