【问题标题】:getRequestProperty("Authorization") always returns nullgetRequestProperty("Authorization") 总是返回 null
【发布时间】:2011-02-21 06:52:04
【问题描述】:

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

我做错了吗?这是“安全”功能吗?有没有办法使用 URLConnection 进行这项工作,还是我需要使用另一个 HTTP 客户端库?

【问题讨论】:

    标签: java http authorization oauth httpurlconnection


    【解决方案1】:

    正如Devon's answer 正确指出的那样:这不是错误,而是“安全”功能?

    但您不必切换到其他库:始终可以通过反射访问底层MessageHeader-collection 并提取“Authorization”-header 值。

    经过一番摸索后,我设法想出了一个有效的snippet here

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这就解释了。以及为什么相同的代码在 Google App Engine 上运行良好(他们使用自己的 HttpUrlConnection 实现)。
      【解决方案3】:

      我对额外的依赖关系不满意,但关注suggestion to switch to Commons Http 为我解决了眼前的问题。

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 同样的结果:另一个头工作,授权保持为空
        • 您是否尝试过类似request.addRequestProperty("Authorization", "Basic " + hashed("username:password")); 的方法,其中hashed 是字符串的Base64 哈希?看看你的assertEquals 是否返回结果。
        • 即便如此,我还是使用了使用 URLConnection 的 OAuth 身份验证,它对我有用。如果这不起作用,请使用 Apache 的 HTTP 客户端(强烈推荐)。
        • 这应该是对帖子的评论。
        猜你喜欢
        • 2018-07-01
        • 2014-03-04
        • 2016-11-02
        • 2014-05-06
        • 2012-06-05
        • 2014-05-30
        • 2014-02-23
        • 2017-10-12
        • 2013-08-16
        相关资源
        最近更新 更多