使用 Java URLConnection 类的代理 [英] Proxy With Java URLConnection class

查看:72
本文介绍了使用 Java URLConnection 类的代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 很陌生.我正在使用以下代码来调用 REST API,它在简单的环境中工作正常,但是当我与代理环境一起使用时,它会抛出 NullPointerException.我在谷歌上发现我们必须为此设置代理设置.我根据 http://www.javaworld.com/javaworld/javatips 设置代理/jw-javatip42.html 文章,但这不起作用 + base64Encode( password ) 创建语法错误.

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.

推荐答案

我怀疑您的 NullPointerException 正在发生,因为 yc.getInputStream() 正在返回 null.在尝试创建读取器以从中读取字节之前,您需要检查它是否返回了一些非空值.

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.

至于代理问题,您可以将一个Proxy对象传递给连接,例如:

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.

这篇关于使用 Java URLConnection 类的代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆