Header values overwritten on redirect in HTTPClient

风流意气都作罢 提交于 2019-12-06 18:16:30

I had the same problem when trying to download files from bitbucket's download section using HttpClient. After the first request bitbucket sends a redirect to CDN which then complains if the Authorization header is set.

I worked around it by changing DefaultRedirectStrategy.getRedirect() method to return redirect object which does not allow Authorization headers to be set.

I work with Scala so here is the code:

val http = new DefaultHttpClient()
http.setRedirectStrategy(new DefaultRedirectStrategy() {
  override def getRedirect(
    request: HttpRequest, response: HttpResponse, context: HttpContext
  ): HttpRequestBase = {
    val uri: URI = getLocationURI(request, response, context)
    val method: String = request.getRequestLine.getMethod
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
      new HttpHead(uri) {
        override def setHeaders(headers: Array[Header]) {
          super.setHeaders(headers.filterNot(_.getName == "Authorization"))
        }
      }
    }
    else {
      new HttpGet(uri) {
        override def setHeaders(headers: Array[Header]) {
          super.setHeaders(headers.filterNot(_.getName == "Authorization"))
        }
      }
    }
  }
})

Please note orig.getAllHeaders() returns an array of headers explicitly added to the message by the caller. The code from DefaultRequestDirector posted above does not copy request headers automatically generated by HttpClient such as Host, Content-Length, Transfer-Encoding and so on.

You post a wire log of the session exhibiting the problem I may be able to tell why redirects do not work as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!