UnknownHostException when attempting to create a HTTPUrlConnection with a proxy

2.2k views Asked by At

Using Java, I am attempting to connect and fetch the response code from http://www.oracle.com via a local proxy http://www-my.proxy.address.com.

I've tried:

public void testAConnection() throws IOException {
    String urlText = "http://www.oracle.com";

    System.setProperty("http.proxyHost", "http://www-my.proxy.address.com");
    System.setProperty("http.proxyPort", "80");

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http://www-my.proxy.address.com", 80));
    URL url = new URL(urlText);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
    int responseCode = conn.getResponseCode();
    System.out.println(responseCode);
}

Which throws:

java.net.UnknownHostException: ...

As well as:

Proxy proxy = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress("http://www-my.proxy.address.com", 80));
URL url = new URL(urlText);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

The latter throws:

ava.lang.IllegalArgumentException: type DIRECT is not compatible with address ...

For others who have solved this problem, the second method seems to usually work. Any help appreciated!

EDIT: After racking my brains trying to figure what was wrong, I restarted my IDE and everything seems to be working. Thanks for your feedback.

3

There are 3 answers

0
R Kaja Mohideen On

Type.HTTP is correct. But, I doubt whether your system is not able to resolve your proxy IP. Check your DNS settings or manually add entry in /etc/hosts for www-my.proxy.address.com

0
Tarek On

You have to connect before calling getResponseCode(), try this code :

 public void testAConnection() throws IOException {
 String urlText = "http://www.oracle.com";
 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http://www-my.proxy.address.com", 80));
 URL url = new URL(urlText);
 HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
 conn.connect();
 int responseCode = conn.getResponseCode();
 System.out.println(responseCode);

}

0
brass monkey On

The http.proxyHost property is expecting a hostname.

http.proxyHost: the host name of the proxy server

You are specifying the proxy also with the protocol (http://). Setting only the hostname should solve the issue.

E.g.

System.setProperty("http.proxyHost", "www-my.proxy.address.com");