6

我需要针对 SOCKS 代理设置代理身份验证。我发现这篇文章给出的说明似乎适用于常见的 HTTP 代理。

        httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);

        HttpState state = new HttpState();
        state.setProxyCredentials(new AuthScope("proxyserver.example.com", 8080), 
           new UsernamePasswordCredentials("username", "password"));
        httpclient.setState(state);

这也适用于SOCKS代理,还是我必须做一些不同的事情?

4

5 回答 5

6

Java 通过首选项支持 Socks 代理配置:

  • socksProxyHost用于 SOCKS 代理服务器的主机名
  • socksProxyPort对于端口号,默认值为1080

例如

java -DsocksProxyHost=socks.mydomain.com

编辑)对于您的示例,如果以前面概述的方式配置了 socks 代理:

httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);
Credentials cred = new UsernamePasswordCredentials("username","password");
httpclient.getState().setProxyCredentials(AuthScope.ANY, cred); 

你也可以使用这个变体(没有 httpclient):

SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); // Type.HTTP for HTTP

所以完成前面的例子,我们现在可以添加:

URL url = new URL("http://java.sun.com/");
URConnection conn = url.openConnection(proxy);

高温高压

于 2009-09-07T11:27:41.830 回答
4

Apache HTTPClient的功能页面说:

使用原生 Java 套接字支持通过 SOCKS 代理(版本 4 和 5)进行透明连接。

使用“透明”,我想他们的意思是它不需要你做任何特别的事情就可以工作。你在某处有可用的 SOCKS 代理吗?你不能试试看它是否有效吗?

于 2009-09-07T11:26:54.873 回答
4

HttpClient 3 本机不支持 SOCKS。您可以按照其他人的建议尝试 JDK 中的 SOCKS 支持。副作用是您的整个 JVM 将通过相同的 SOCKS 代理。

Java 5 支持 SOCKS(类型 2)中的用户名/密码认证。您所要做的就是像这样设置身份验证器,

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});

同样,这可能对您不起作用,因为它会影响 JVM 中的所有身份验证(HTTP 身份验证、代理身份验证)。

于 2009-09-07T11:56:54.950 回答
3

You can provide a custom socket factory which implements the SOCKS protocol, and register it as your default HTTP protocol handler. This solution has a limitation similar to tuergeist's answer above has - it applies globally, to any HTTP connection you'll establish through HttpClient.

If you find this a problem, take a look at this correspondence, where Oleg suggests using HttpClient 4.0, but also refers to a possible patch in HostConfiguration class for HttpClient 3.x.

Another possible solution, which is my personal favorite, is to write a wrapper HTTP proxy to the socks proxy.

于 2009-11-29T09:56:56.763 回答
1

I tried

System.setProperty("socksProxyHost", "socks.xyz.com");
System.setProperty("socksProxyPort", "1000");

and it's working fine.

于 2010-06-20T05:13:16.827 回答