HTTP Builder/Groovy - lost 302 (redirect) handling?

纵然是瞬间 提交于 2019-12-03 14:28:06

I've had the same problem with HTTPBuilder until I realized that the HTTP/1.1 spec states:

Redirection 3xx

[..] This class of status code indicates that further action needs to be
taken by the user agent in order to fulfill the request. The action
required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD.

302 Found

[..] If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Essentially this means that the request following a POST and 302 redirect won't work automatically and will require user intervention if the HTTP/1.1 spec is followed by the letter. Not all Http clients follow this practice, in fact most browsers do not. However the Apache Http Client (which is the underlying Http client for HttpBuilder) is spec compliant. There is an issue in the Apache Http Client bugtracker that contains more information and a possible solution for the problem.

void test_myPage_shouldRedirectToLogin() {
  def baseURI = "http://servername"
  def httpBuilder = new HTTPBuilder(baseURI)
  // Make sure that HttpClient doesn't perform a redirect
  def dontHandleRedirectStrategy = [
    getRedirect : { request, response, context -> null},
    isRedirected : { request, response, context -> false}
  ]
  httpBuilder.client.setRedirectStrategy(dontHandleRedirectStrategy as RedirectStrategy)

  // Execute a GET request and expect a redirect
  httpBuilder.request(Method.GET, ContentType.TEXT) {
    req ->
      uri.path = '/webapp/de/de/myPage'
      response.success = { response, reader ->
        assertThat response.statusLine.statusCode, is(302)
        assertThat response.headers['Location'].value, startsWith("${baseURI}/webapp/login")
      }
      response.failure = { response, reader ->
        fail("Expected redirect but received ${response.statusLine} \n ${reader}")
      }
    }
  }

302 status coming because, after action on any link redirected url not follow by HttpBuilder so we need to add "RedirectStrategy" explicitly.

What other headers do you see when you process the 302 response? If you were to turn on http client logging you'd expect to see HttpClient process the 302 response and automatically request URL in the Location header. What do you see when you process that URL? Does it work for any URL?

Try http://www.sun.com (it redirects to Oracle now.) I'm just wondering if the server you're working with is doing something wonky like sending a 302 with no Location header.

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