我在此处尝试使用建议的代码时发现了一个奇怪的行为。
看来,在设置了默认 ProxySelector 后,常规套接字代码(例如创建新套接字)不再起作用,因为它尝试使用 socks 服务器(不知道为什么会这样做,但对我来说确实如此) .
所以如果你在打电话的时候
Socket socket = new Socket(host, port);
你收到这样的 SocketException:
java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
然后尝试将默认 ProxySelector 设置回 null:
ProxySelector.setDefault(null);
对我来说,这导致了以下小型 Java 类,我现在使用它来简单地检索系统代理设置,而不会影响应用程序的 Sockets() 的进一步使用,同时正确配置系统以使用代理:
public class ProxyConfig {
private static String host;
private static int port;
public static void init() {
System.setProperty("java.net.useSystemProxies", "true");
Proxy proxy = getProxy();
if (proxy != null) {
InetSocketAddress addr = (InetSocketAddress) proxy.address();
host = addr.getHostName();
port = addr.getPort();
System.setProperty("java.net.useSystemProxies", "false");
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", ""+port);
}
System.setProperty("java.net.useSystemProxies", "false");
}
public static String getHost() {
return host;
}
public static int getPort() {
return port;
}
private static Proxy getProxy() {
List<Proxy> l = null;
try {
ProxySelector def = ProxySelector.getDefault();
l = def.select(new URI("http://foo/bar"));
ProxySelector.setDefault(null);
} catch (Exception e) {
e.printStackTrace();
}
if (l != null) {
for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
java.net.Proxy proxy = iter.next();
return proxy;
}
}
return null;
}
}