getRequestProperty(“Authorization”)始终返回null

我正在尝试读取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")); } 

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

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

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

我对额外的依赖关系并不满意,但是根据建议切换到Commons Http解决了我的直接问题。

我仍然想知道原始代码的问题是什么。