getRequestProperty("Authorization") 总是返回 null [英] getRequestProperty("Authorization") always returns null

查看:47
本文介绍了getRequestProperty("Authorization") 总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取 HTTP 请求的授权标头(因为我需要向其中添加一些内容),但我始终为标头值获取 null.其他标题工作正常.

I am trying to read the authorization header for an HTTP request (because I need to add something to it), but I always get null for the header value. Other headers work fine.

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 客户端库?

Am I doing something wrong? Is this a "security" feature? Is there a way to make this work with URLConnection, or do I need to use another HTTP client library?

推荐答案

显然,这是一个安全功能".URLConnection 实际上是 sun 的一个实例.net.www.protocol.http.HttpURLConnection.它定义 getRequestProperty 为:

Apparently, it's a security "feature". The URLConnection is actually an instance of sun.net.www.protocol.http.HttpURLConnection. It defines getRequestProperty as:

    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"
   };

这篇关于getRequestProperty("Authorization") 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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