getRequestProperty("Authorization")始终返回null

Thi*_*ilo 15 java authorization http oauth httpurlconnection

我正在尝试读取HTTP请求的授权标头(因为我需要向其添加内容),但我总是为标头值获取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"));
}
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?这是一个"安全"功能吗?有没有办法使这个工作与URLConnection,或者我是否需要使用另一个HTTP客户端库?

Dev*_*ler 25

显然,这是一个安全"功能".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);
    }
Run Code Online (Sandbox Code Playgroud)

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"
   };
Run Code Online (Sandbox Code Playgroud)