Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy With Java URLConnection class

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.

like image 905
Govind Malviya Avatar asked Nov 25 '11 04:11

Govind Malviya


People also ask

How do I make HttpURLConnection use a proxy?

Type. HTTP, new InetSocketAddress("10.0. 0.1", 8080)); conn = new URL(urlString). openConnection(proxy);

What is URLConnection class in Java?

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.


1 Answers

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.

like image 94
Gian Avatar answered Oct 14 '22 00:10

Gian