我正在尝试读取HTTP请求的authorization标头(因为我需要向其添加一些内容),但标头值总是为null。其他标头工作正常。
public void testAuth() throws MalformedURLException, IOException{
URLConnection request = new URL("http://google.com").openConnection();
request.setRequestProperty("Authorization", "MyHeader");
request.setRequestProperty("Stackoverflow", "anotherHeader");
// works fine
assertEquals("anotherHeader", request.getRequestProperty("Stackoverflow"));
// Auth header returns null
assertEquals("MyHeader", request.getRequestProperty("Authorization"));
}我做错了什么吗?这是一个“安全”特性吗?有没有办法让它与URLConnection一起工作,或者我需要使用另一个HTTP客户端库?
发布于 2010-05-19 20:40:46
显然,这是一个安全“功能”。URLConnection实际上是sun.net.www.protocol.http.HttpURLConnection的一个实例。它将getRequestProperty定义为:
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);
}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"
};发布于 2010-05-19 17:22:29
我对额外的依赖项并不满意,但是遵循suggestion to switch to Commons Http为我解决了直接的问题。
我仍然想知道我的原始代码有什么问题。
发布于 2021-10-13 21:50:38
正如Devon's answer所说的那样:这不是一个bug,而是一个“安全”特性
但是您不必切换到不同的库:始终可以通过反射访问底层的授权-collection并提取“-header”Authorization值。
经过一些头疼之后,我终于想出了一个可以工作的snippet here。
https://stackoverflow.com/questions/2864062
复制相似问题