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);
}