Connect to a site using proxy code in java

后端 未结 3 921
北荒
北荒 2021-01-03 05:53

I want to connect to as site through proxy in java. This is the code which I have written:

public class ConnectThroughProxy 
{
    Proxy proxy = new Proxy(Pr         


        
相关标签:
3条回答
  • 2021-01-03 06:23

    It seems to me, that you are not using your Proxy instance at all. I think you should pass it when you are creating URLConnection instance:

    URLConnection connection=url.openConnection(proxy);
    

    Setting of environment properties http.proxy is easier and when using some 3rd party libraries without Proxy instance passing support only possible solution, but its drawback is that it is set globally for the whole process.

    0 讨论(0)
  • 2021-01-03 06:26

    I was using the Google Data APIs and the only way I got the proxy settings to work was to provide ALL the parameters related to proxy, even thought they are set to be empty:

    /usr/java/jdk1.7.0_04/bin/java -Dhttp.proxyHost=10.128.128.13 
        -Dhttp.proxyPassword -Dhttp.proxyPort=80 -Dhttp.proxyUserName 
        -Dhttps.proxyHost=10.128.128.13 -Dhttps.proxyPassword -Dhttps.proxyPort=80 
        -Dhttps.proxyUserName com.stackoverflow.Runner
    

    Where, username and password are NOT required, and the same http and https servers are set to be the same, as well as the port number (if that's your case as well). Note that the same HTTP proxy is also provided as the HTTPS server, as well as its port number (reference from https://code.google.com/p/syncnotes2google/issues/detail?id=2#c16).

    If your Java class has an instance of the class "URL", it should pick those configurations up...

    0 讨论(0)
  • 2021-01-03 06:37

    If you're just trying to make HTTP requests through an HTTP proxy server, you shouldn't need to go to this much effort. There's a writeup here: http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

    But it basically boils down to just setting the http.proxyHost and http.proxyPort environment properties, either on the command line, or in code:

    // Set the http proxy to webcache.mydomain.com:8080
    System.setProperty("http.proxyHost", "webcache.mydomain.com");
    System.setProperty("http.proxyPort", "8080");
    
    // Next connection will be through proxy.
    URL url = new URL("http://java.sun.com/");
    InputStream in = url.openStream();
    
    // Now, let's 'unset' the proxy.
    System.clearProperty("http.proxyHost");
    
    // From now on HTTP connections will be done directly.
    
    0 讨论(0)
提交回复
热议问题