我有一個代理列表來測試它們是HTTP還是Socks代理,但下面的Java代碼在它調用connection.getContent()或connection.getInputStream()時會掛起。我觀察到,當代理服務器無法響應並且代碼塊等待服務器響應時,會發生此問題,當服務器無法響應時,如何防止此代碼永久掛起/阻止,以便可以檢查下一個代理。如何防止掛起此Java代碼
import java.io.*;
import java.net.*;
import java.util.*;
public class ProxyTest {
public static void main(String[] args) throws IOException {
InetSocketAddress proxyAddress = new InetSocketAddress("myproxyaddress", 1234);
Proxy.Type proxyType = detectProxyType(proxyAddress);
}
public static Proxy.Type detectProxyType(InetSocketAddress proxyAddress) throws IOException {
URL url = new URL("http://www.google.com/");
List<Proxy.Type> proxyTypesToTry = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);
for(Proxy.Type proxyType : proxyTypesToTry) {
Proxy proxy = new Proxy(proxyType, proxyAddress);
URLConnection connection = null;
try {
connection = url.openConnection(proxy);
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.getContent();
//connection.getInputStream();
return(proxyType);
}
catch (SocketException e) {
e.printStackTrace();
}
}
return(null);
}
}
我試過這個,但線程t永遠不會停止/完成它將掛起connection.getContent()被調用時。 – John 2012-07-20 20:03:05
對於線索建議+1。這是使非阻塞(至少在主線程上)請求的方式。 @john您可以隨時調用Thread.interupt(),並讓該線程檢查它是否應該自行停止。 – hsanders 2012-07-20 20:21:09