代码之家  ›  专栏  ›  技术社区  ›  Thilo

GetRequestProperty(“授权”)始终返回空值

  •  14
  • Thilo  · 技术社区  · 14 年前

    我正在尝试读取HTTP请求的授权头(因为我需要向其添加一些内容),但头值总是为空。其他收割台工作正常。

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

    3 回复  |  直到 14 年前
        1
  •  24
  •   Devon_C_Miller    14 年前

    显然,这是一个安全“特性”。URLConnection实际上是 sun.net.www.protocol.http.HttpURLConnection . 它定义 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"
       };
    
        2
  •  0
  •   Buhake Sindi Tesnep    14 年前

    你试过用吗 URLConnection.addRequestProperty() ? 这是我用来添加HTTP请求头的方法。

        3
  •  0
  •   Community CDub    7 年前

    我对额外的依赖并不满意,但是遵循 suggestion to switch to Commons Http 为我解决了眼前的问题。

    我还是想知道我的原始代码出了什么问题。