Proxy With Java URLConnection class

坚强是说给别人听的谎言 提交于 2019-12-07 06:05:42

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8264889/proxy-with-java-urlconnection-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!