10

我使用 100% 工作袜子,但无法通过我的应用程序连接。

        SocketAddress proxyAddr = new InetSocketAddress("1.1.1.1", 12345);
        Proxy pr = new Proxy(Proxy.Type.SOCKS, proxyAddr);

    try
    {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(pr);
        con.setConnectTimeout(proxyTimeout * 1000);
        con.setReadTimeout(proxyTimeout * 1000);
        con.connect();

        System.out.println(con.usingProxy());
    }
    catch(IOException ex)
    {
        Logger.getLogger(Enter.class.getName()).log(Level.SEVERE, null, ex);
    }

那么我做错了什么?如果我将 HTTP 与一些 HTTP 代理一起使用,那么一切都可以正常工作,但不能与 SOCKS 一起使用。

4

4 回答 4

24

这真的很容易。您只需要设置相关的系统属性,然后继续使用您的常规 HttpConnection。

System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "socksProxyHost", "127.0.0.1" );
System.getProperties().put( "socksProxyPort", "1234" );
于 2012-08-25T14:42:56.287 回答
6

Inform the "socksProxyHost" and "socksProxyPort" VM arguments.

e.g.

java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main
于 2017-11-30T21:59:11.610 回答
2

http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/net/www/http/HttpClient.java/?v=source

深入浅出,HttpClient 用在 HttpURLConnection 中。

if ((proxy != null) && (proxy.type() == Proxy.Type.HTTP)) {
   sun.net.www.URLConnection.setProxiedHost(host);
   privilegedOpenServer((InetSocketAddress) proxy.address());
   usingProxy = true;
   return;
} else {
   // make direct connection
   openServer(host, port);
   usingProxy = false;
   return;
}

在第 476 行,您可以看到唯一可接受的代理是 HTTP 代理。否则它会直接连接。

奇怪的是,不支持使用 HttpURLConnection 的 SOCKS 代理。更糟糕的是,代码甚至没有使用不受支持的代理,只是忽略了代理!

为什么在此类存在至少 10 年之后对 SOCKS 代理没有任何支持,无法解释。

于 2015-12-07T05:42:44.890 回答
1

或者这个答案:https ://stackoverflow.com/a/64649010/5352325

如果你知道哪些URI需要去代理,你也可以使用底层的ProxySelector:https ://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html where for each Socket connection即,您可以决定要使用哪些代理。

它看起来像这样:

public class MyProxySelector extends ProxySelector {
        ...

        public java.util.List<Proxy> select(URI uri) {
        ...
          if (uri is what I need) {
             return list of my Proxies
          }
        ...
        }
        ...
}
 

然后你使用你的选择器:

public static void main(String[] args) {
        MyProxySelector ps = new MyProxySelector(ProxySelector.getDefault());
        ProxySelector.setDefault(ps);
        // rest of the application
}
于 2020-11-02T16:12:32.950 回答