在 URL 对象中设置自定义 HTTP 请求标头不起作用
我正在尝试使用 HTTP 从 IP 摄像机获取图像。相机需要 HTTP 基本身份验证,因此我必须添加相应的请求标头:
URL url = new URL("http://myipcam/snapshot.jpg");
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization",
"Basic " + new String(Base64.encode("user:pass".getBytes())));
// outputs "null"
System.out.println(uc.getRequestProperty("Authorization"));
稍后我将 url
对象传递给 ImageIO.read()
,并且,您可以我猜,尽管 user
和 pass
是正确的,但我收到了 HTTP 401 Unauthorized。
我做错了什么?
我也尝试过 new URL("http://user:pass@myipcam/snapshot.jpg")
,但这也不起作用。
I am trying to fetch an image from an IP camera using HTTP. The camera requires HTTP basic authentication, so I have to add the corresponding request header:
URL url = new URL("http://myipcam/snapshot.jpg");
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization",
"Basic " + new String(Base64.encode("user:pass".getBytes())));
// outputs "null"
System.out.println(uc.getRequestProperty("Authorization"));
I am later passing the url
object to ImageIO.read()
, and, as you can guess, I am getting an HTTP 401 Unauthorized, although user
and pass
are correct.
What am I doing wrong?
I've also tried new URL("http://user:pass@myipcam/snapshot.jpg")
, but that doesn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在类
sun.net.www.protocol.http.HttpURLConnection
,它扩展了java.net.HttpURLConnection
,请求安全敏感信息时,以下方法getRequestProperty(String key)
被重写以返回null
。以下是
EXCLUDE_HEADERS
的声明:这就是
uc.getRequestProperty("Authorization")
上的null
的原因。您是否尝试过使用 Apache 的 HttpClient ?In class
sun.net.www.protocol.http.HttpURLConnection
, which extendsjava.net.HttpURLConnection
, the following methodgetRequestProperty(String key)
was overridden to returnnull
when requesting security sensitive information.Here is the declaration for
EXCLUDE_HEADERS
:That's why you're having a
null
onuc.getRequestProperty("Authorization")
. Have you tried using HttpClient from Apache?问题已解决。它不起作用,因为我将
url
传递给ImageIO.read()
。相反,传递 uc.getInputStream() 使其正常工作。
Issue resolved. It didn't work because I was passing
url
toImageIO.read()
.Instead, passing
uc.getInputStream()
got it working.您是否尝试过对
URLConnection
或HttpURLConnection
进行子类化并重写getRequestProperty()
方法?Have you tried to subclass
URLConnection
orHttpURLConnection
and override thegetRequestProperty()
method?