本文介绍了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实际上是。它将 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(&quot; Authorization&quot;)始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:29