本文共 668 字,大约阅读时间需要 2 分钟。
java中HttpClient如何才能获取302重定向的新网址呢?下面给出解决办法:
HttpClient默认是直接进行重定向的,首先要阻止它进行重定向(302跳转)。
//设置不允许重定向RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();//使用 CloseableHttpClient 而非 HttpClientCloseableHttpClient 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);}
转载地址:http://fdwmf.baihongyu.com/