欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用HttpClient获取302重定向后的目标网页地址

最编程 2024-02-17 17:58:45
...

java中HttpClient如何才能获取302重定向的新网址呢?下面给出解决办法:

HttpClient默认是直接进行重定向的,首先要阻止它进行重定向(302跳转)。

//设置不允许重定向
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();

//使用 CloseableHttpClient 而非 HttpClient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build(); 
HttpResponse response = httpClient.execute(new HttpGet("http://...."));

int code = response.getStatusLine().getStatusCode();
String newuri="";
if (code == 302) {
   Header header = response.getFirstHeader("location"); // 跳转的目标地址是在response的 HTTP-HEAD 中的,location的值
   newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
   System.out.println(newuri);
}

 

推荐阅读