gpt4 book ai didi

java - 每个线程使用自己的代理

转载 作者:可可西里 更新时间:2023-11-01 16:25:47 24 4
gpt4 key购买 nike

我正在尝试设置一个 Java 程序,其中每个线程都可以使用自己的代理。

目前我只找到了一种全局设置代理的方法。 ( http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html )

As mentioned earlier, these settings affect all http connections during the entire lifetime of the VM invoked with these options. However it is possible, using the System.setProperty() method, to have a slightly more dynamic behavior.

Here is a code excerpt showing how this can be done:

//Set the http proxy to webcache.mydomain.com:8080

System.setProperty("http.proxyHost", "webcache.mydomain.com"); System.setPropery("http.proxyPort", "8080");

更新

我尝试使用代理类,但是当我不想使用所述代理时无法创建直接连接:

private void setProxy()
{
if(proxyUrl != null)
{
SocketAddress addr = new InetSocketAddress(proxyUrl, proxyPort);
proxy = new Proxy(Proxy.Type.HTTP, addr);
}
else
{
proxy = new Proxy(Proxy.Type.DIRECT, null);
}
}

Exception in .... java.lang.IllegalArgumentException: 类型 DIRECT 与地址 null 不兼容

我怎样才能使它适用于直接连接?还没有尝试过代理。

最佳答案

也许使用 Proxy解释类here在第 3 节中:

As we have seen, the system properties are powerful, but not flexible. The "all or nothing" behavior was justly deemed too severe a limitation by most developers. That's why it was decided to introduce a new, more flexible, API in J2SE 5.0 so that it would be possible to have connection based proxy settings.

你可以使用 Proxy.NO_PROXY到:

... not to use any proxying.

做这样的事情:

private void setProxy()
{
if(proxyUrl != null)
{
SocketAddress addr = new InetSocketAddress(proxyUrl, proxyPort);
proxy = new Proxy(Proxy.Type.HTTP, addr);
}
else
{
proxy = Proxy.NO_PROXY;
}
}

关于java - 每个线程使用自己的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com