HttpClient 4 - how to capture last redirect URL

后端 未结 8 1909
北恋
北恋 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:25

    In version 2.3 Android still do not support following redirect (HTTP code 302). I just read location header and download again:

    if (statusCode != HttpStatus.SC_OK) {
        Header[] headers = response.getHeaders("Location");
    
        if (headers != null && headers.length != 0) {
            String newUrl = headers[headers.length - 1].getValue();
            // call again the same downloading method with new URL
            return downloadBitmap(newUrl);
        } else {
            return null;
        }
    }
    

    No circular redirects protection here so be careful. More on by blog Follow 302 redirects with AndroidHttpClient

    0 讨论(0)
  • 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<T> 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<T> result = client.execute(request, handler, context);
    URI finalUrl = request.getURI();
    List<URI> locations = context.getRedirectLocations();
    if (locations != null) {
        finalUrl = locations.get(locations.size() - 1);
    }
    
    0 讨论(0)
提交回复
热议问题