HttpClient 4 - how to capture last redirect URL

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

    That would be the current URL, which you can get by calling

      HttpGet#getURI();
    

    EDIT: You didn't mention how you are doing redirect. That works for us because we handle the 302 ourselves.

    Sounds like you are using DefaultRedirectHandler. We used to do that. It's kind of tricky to get the current URL. You need to use your own context. Here are the relevant code snippets,

            HttpGet httpget = new HttpGet(url);
            HttpContext context = new BasicHttpContext(); 
            HttpResponse response = httpClient.execute(httpget, context); 
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw new IOException(response.getStatusLine().toString());
            HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute( 
                    ExecutionContext.HTTP_REQUEST);
            HttpHost currentHost = (HttpHost)  context.getAttribute( 
                    ExecutionContext.HTTP_TARGET_HOST);
            String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
    

    The default redirect didn't work for us so we changed but I forgot what was the problem.

提交回复
热议问题