HttpClient 4 - how to capture last redirect URL

后端 未结 8 1958
北恋
北恋 2020-11-29 18:53

I have rather simple HttpClient 4 code that calls HttpGet to get HTML output. The HTML returns with scripts and image locations all set to local (e.g.

8条回答
  •  伪装坚强ぢ
    2020-11-29 19:26

    In HttpClient 4, if you are using LaxRedirectStrategy or any subclass of DefaultRedirectStrategy, this is the recommended way (see source code of DefaultRedirectStrategy) :

    HttpContext context = new BasicHttpContext();
    HttpResult result = client.execute(request, handler, context);
    URI finalUrl = request.getURI();
    RedirectLocations locations = (RedirectLocations) context.getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
    if (locations != null) {
        finalUrl = locations.getAll().get(locations.getAll().size() - 1);
    }
    

    Since HttpClient 4.3.x, the above code can be simplified as:

    HttpClientContext context = HttpClientContext.create();
    HttpResult result = client.execute(request, handler, context);
    URI finalUrl = request.getURI();
    List locations = context.getRedirectLocations();
    if (locations != null) {
        finalUrl = locations.get(locations.size() - 1);
    }
    

提交回复
热议问题