2010-05-19 100 views
12

我想读HTTP请求的授权头(因为我需要添加一些东西给它),但我总是得到空头值。其他头文件工作正常。getRequestProperty(“授权”)总是返回空

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

回答

21

显然,这是一个安全“功能”。 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" 
    }; 
+1

这将解释它。此外,为什么相同的代码在Google App Engine上运行良好(他们使用自己的HttpUrlConnection实现)。 – Thilo 2010-05-21 07:18:52

0

您是否尝试过使用URLConnection.addRequestProperty()? 这是我用来添加HTTP请求标题的方式。

+0

相同的结果:另一头的作品,授权撑空 – Thilo 2010-05-19 09:05:05

+0

您是否尝试过类似 'request.addRequestProperty(”授权“,”基本“+散列(”用户名:密码“));'哪里'散列'是字符串的Base64散列? 看看你的'assertEquals'是否返回结果。 – 2010-05-19 09:12:14

+0

我没有使用基本身份验证。 – Thilo 2010-05-19 09:13:33