How do I implement a HttpURLConnection using a Proxy ?

0 votes

When I write the code given below:

conn = new URL(urlString).openConnection();
System.out.println("Proxy? " + conn.usingProxy());

it is giving the output:

Proxy? false

The problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.

Dec 10, 2018 in Java by Rishabh
• 3,540 points

edited Dec 10, 2018 by Rishabh 308 views

1 answer to this question.

0 votes

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy) method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

In case your proxy requires authentication it will give you a response 407.

For your scenario I suggest you the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);
answered Dec 10, 2018 by Sushmita
• 6,880 points

Related Questions In Java

0 votes
2 answers

How do I get the current date and time using Java?

If you require a time stamp in ...READ MORE

answered Aug 23 in Java by Sirajul
• 37,480 points
119 views
0 votes
1 answer

How do I fix a NullPointerException?

When you declare a reference variable (i.e. ...READ MORE

answered Apr 13, 2018 in Java by parth295
• 4,640 points
104 views
0 votes
1 answer

How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

answered Apr 19, 2018 in Java by Rishabh
• 3,540 points
107 views
0 votes
2 answers
0 votes
2 answers

Ho do I Iterate through a HashMap which contains duplicate values

for (Map.Entry<String, String> item : params.entrySet()) { ...READ MORE

answered Jul 24, 2018 in Java by samarth295
• 2,190 points
186 views
0 votes
2 answers

Performing Iteration over each entry in a 'Map'

In Java 8 you can do it ...READ MORE

answered Oct 24, 2018 in Java by Sushmita
• 6,880 points
62 views
0 votes
2 answers
0 votes
1 answer

How can I Sort an ArrayList in Java

You can sort the ArrayList in 2 ...READ MORE

answered Apr 23, 2018 in Java by sharth
• 3,350 points
77 views
0 votes
2 answers

How do I rename a file using Java

// File (or directory) with old name File ...READ MORE

answered Oct 5, 2018 in Java by Sushmita
• 6,880 points
61 views
0 votes
2 answers

How can I sort values of a Map in Java using its key

Assuming TreeMap is not good for you ...READ MORE

answered Oct 10, 2018 in Java by Sushmita
• 6,880 points
71 views