我有一个代理列表来测试它们是 HTTP 代理还是 Socks 代理,但是下面的 Java 代码在调用 connection.getContent() 或 connection.getInputStream() 时会挂起。我观察到当代理服务器无法响应并且代码阻塞等待服务器响应时会发生此问题,如何防止此代码在服务器无法响应时永远挂起/阻塞,以便检查下一个代理。
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);
}
}