[英]Setting custom HTTP request headers in an URL object doesn't work
I am trying to fetch an image from an IP camera using HTTP. 我试图使用HTTP从IP摄像头获取图像。 The camera requires HTTP basic authentication, so I have to add the corresponding request header:
相机需要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"));
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. 我稍后将
url
对象传递给ImageIO.read()
,并且,正如您所猜测的,我得到的是HTTP 401 Unauthorized,尽管user
和pass
是正确的。
What am I doing wrong? 我究竟做错了什么?
I've also tried new URL("http://user:pass@myipcam/snapshot.jpg")
, but that doesn't work either. 我也尝试了
new URL("http://user:pass@myipcam/snapshot.jpg")
,但这也不起作用。
In class sun.net.www.protocol.http.HttpURLConnection
, which extends java.net.HttpURLConnection
, the following method getRequestProperty(String key)
was overridden to return null
when requesting security sensitive information. 在类
sun.net.www.protocol.http.HttpURLConnection
,它扩展了java.net.HttpURLConnection
,在请求安全敏感信息时,重写了以下方法getRequestProperty(String key)
以返回null
。
public String getRequestProperty(String key) {
// don't return headers containing security sensitive information
if (key != null) {
for (int i = 0; i < EXCLUDE_HEADERS.length; i++) {
if (key.equalsIgnoreCase(EXCLUDE_HEADERS[i])) {
return null;
}
}
}
return requests.findValue(key);
}
Here is the declaration for EXCLUDE_HEADERS
: 这是
EXCLUDE_HEADERS
的声明:
// the following http request headers should NOT have their values
// returned for security reasons.
private static final String[] EXCLUDE_HEADERS = {
"Proxy-Authorization", "Authorization" };
That's why you're having a null
on uc.getRequestProperty("Authorization")
. 这就是你在
uc.getRequestProperty("Authorization")
上使用null
的原因。 Have you tried using HttpClient from Apache? 您是否尝试过使用Apache的HttpClient ?
Issue resolved. 问题解决了。 It didn't work because I was passing
url
to ImageIO.read()
. 它没有用,因为我将
url
传递给ImageIO.read()
。
Instead, passing uc.getInputStream()
got it working. 相反,传递
uc.getInputStream()
使它工作。
您是否尝试URLConnection
或HttpURLConnection
并覆盖getRequestProperty()
方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.