有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在尝试设置一个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");

更新

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

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: type DIRECT is not compatible with address null

我怎样才能让这个直接连接工作?还没有试过代理


共 (2) 个答案

  1. # 1 楼答案

    Barry NL的解决方案是半有效的,因为我不知道如何在该解决方案中不使用代理

    我想到的是:

    proxyUrlproxyPort在我的类的构造函数中

    如果我只设置了^{,我就无法调用url.openConnection(proxy);

    或者proxy = new Proxy(Proxy.Type.DIRECT, null);。 所以我写了我自己的openConnection

    private void setProxy()
    {
        if(proxyUrl != null)
        {
            SocketAddress addr = new InetSocketAddress(proxyUrl, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, addr);
        }
        else
        {
            proxy = null;
        }       
    }
    private URLConnection openConnection2(URL url)
    {
        try {
            if(proxy != null)               
                return url.openConnection(proxy);               
            else 
                return url.openConnection();            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }   
    }
    

    在建立任何连接之前必须调用setProxy()

    我也换了

    url = new URL(http_url);
    con = (HttpURLConnection)url.openConnection(proxy);
    

    url = new URL(http_url);
    con = (HttpURLConnection)openConnection2(url);  
    
  2. # 2 楼答案

    可以使用第3节中解释的Proxyhere

    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;
        }       
    }