HttpClient获取302重定向的新网址方法

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);
}
原创文章 42 获赞 26 访问量 4万+

猜你喜欢

转载自blog.csdn.net/david_pfw/article/details/105991170