简体   繁体   中英

How to get URL connection using proxy in java?

I am trying to create URL connection using a proxy at run time. My code is below:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));
HttpURLConnection connection =
    (HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);

But this is not working. Anybody know why?

adding answer for the help of future visitors

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));
HttpURLConnection connection =(HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "text/xml");
connection.setRequestProperty("Accept", "text/xml, application/xml");
connection.setRequestMethod("POST");

dku.rajkumar 's way doesn't work with me.

I try this and it work. But it takes double time.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));

    HttpURLConnection connection =
        (HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);
    ((HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy)).getInputStream();

System.out.println(connection.usingProxy());

the result is true

without ((HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy)).getInputStream();

the result is false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM