java 在 URL 对象中设置自定义 HTTP 请求标头不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6469540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting custom HTTP request headers in an URL object doesn't work
提问by Blagovest Buyukliev
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:
我正在尝试使用 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"));
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")
,但这也不起作用。
采纳答案by Blagovest Buyukliev
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()
让它起作用。
回答by Buhake Sindi
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")
. Have you tried using HttpClientfrom Apache?
这就是为什么你有一个null
on uc.getRequestProperty("Authorization")
。您是否尝试过使用Apache 的HttpClient?
回答by William Niu
Have you tried to subclass URLConnection
or HttpURLConnection
and override the getRequestProperty()
method?
您是否尝试过子类化URLConnection
或HttpURLConnection
覆盖该getRequestProperty()
方法?