Proxy With Java URLConnection class

Govind Malviya picture Govind Malviya · Nov 25, 2011 · Viewed 21k times · Source

I am very new with Java. I am using following code for the calling REST API, its working fine in simple environment but when I used with proxy environment Its throwing the NullPointerException. I found result on google that we have to set proxy setting for that. I set proxy according to that http://www.javaworld.com/javaworld/javatips/jw-javatip42.html article but this is not working + base64Encode( password ) creating syntax error.

URL url = new URL("http://examplerestapi/get/user");
URLConnection yc = url.openConnection();



in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null) {
       sb.append(inputLine);
}

String res = sb.toString();

please help me to set proxy Host, port , username and password.

Answer

Gian picture Gian · Nov 25, 2011

I suspect your NullPointerException is occurring because yc.getInputStream() is returning null. You need to check that it is returning some non-null value before you attempt to create a reader to read bytes from it.

As for the proxy issue, you can pass a Proxy object to the connection, e.g.:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("my.proxy.example.com", 3128));
URLConnection yc = url.openConnection(proxy);

This might at least allow you to interrogate the Proxy and rule out potential sources for the problem (there are several, as it stands).

This thread might have some useful hints for getting your proxy username and password string working properly. The article you linked looks slightly out of date.