简体   繁体   English

代理使用Java URLConnection类

[英]Proxy With Java URLConnection class

I am very new with Java. 我是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 . 我正在使用以下代码来调用REST API,它在简单的环境中工作正常,但是当我使用代理环境时它抛出了NullPointerException I found result on google that we have to set proxy setting for that. 我在google上找到了我们必须为其设置代理设置的结果。 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. 我根据http://www.javaworld.com/javaworld/javatips/jw-javatip42.html文章设置代理,但这不起作用+ base64Encode(密码)创建语法错误。

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. 请帮我设置代理主机,端口,用户名和密码。

I suspect your NullPointerException is occurring because yc.getInputStream() is returning null . 我怀疑你的NullPointerException正在发生,因为yc.getInputStream()返回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, eg: 至于代理问题,您可以将Proxy对象传递给连接,例如:

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. 您链接的文章看起来有点过时了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM