Getting URL after a redirect using HttpClient.Execute(HttpGet)

大城市里の小女人 提交于 2019-11-28 12:17:32

Check out w3c documentation:

10.3.3 302 Found

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

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.

One solution is to use POST method to break auto-redirecting at client side:

HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/");
HttpResponse response1 = httpclient.execute(request1);

// expect a 302 response.
if (response1.getStatusLine().getStatusCode() == 302) {
  String redirectURL = response1.getFirstHeader("Location").getValue();

  // no auto-redirecting at client side, need manual send the request.
  HttpGet request2 = new HttpGet(redirectURL);
  HttpResponse response2 = httpclient.execute(request2);

  ... ...
}

Hope this helps.

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