我有以下代码块:
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毫秒.我在这里错过了什么?无论网络状态和网站的可用性如何,上述块都不应该在半秒内终止?
我正在尝试排序SOCKS代理列表,并找出哪些连接和读取时间小于1000毫秒,这是我的代码
for(Proxy p : proxies) {
try {
URLConnection testConnection = testUrl.openConnection(p);
testConnection.setConnectTimeout(TIMEOUT_VALUE);
testConnection.setReadTimeout(TIMEOUT_VALUE);
success.add(p);
} catch(SocketTimeoutException ste) {
System.out.println("Proxy " + p.address().toString() + " timed out.");
}
}
Run Code Online (Sandbox Code Playgroud)
但是他们中的每一个人都通过了测试,即使我做了TIMEOUT_VALUE = 1;什么我做错了什么?谢谢你的帮助.