[HttpClient]: How to find the final URI after redirects

来源:互联网 发布:copy软件 编辑:程序博客网 时间:2024/05/05 04:11

1.  Use a local HttpContext

To get final request location: -------- HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("https://localhost/"); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(httpget, context); HttpEntity entity = response.getEntity(); if (entity != null) {     entity.consumeContent(); } HttpUriRequest request = (HttpUriRequest) context.getAttribute(         ExecutionContext.HTTP_REQUEST); System.out.println(request.getURI()); 


2. User a custom RedirectStrategy

To get all intermediate redirect locations: -------- DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {     @Override     public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {         URI uri = super.getLocationURI(response, context);         System.out.println("redirect - > " + uri);         return uri;     }     });         HttpGet httpget = new HttpGet("https://localhost/"); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) {     entity.consumeContent(); } 


Reference:

http://old.nabble.com/Finding-out-the-URL-after-a-redirect-td20433446.html

http://old.nabble.com/POST-response-with-status-302-doesn't-redirect-td30134484.html

原创粉丝点击