调用第三方接口之后,发现对方返回的url经过重定向了,而调用doGet方法始终会抛出重定向的异常,该接口一直获取不到正常返回值。
正如图中所示,也就是重定向异常失效的意思。
解决办法如下:
String url = "https://abc.com/login"+ "?id=" + MD5.sign("xxx") + "&password=" + "xxx";
logger.info("request url : " + url);
try{
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpResponse response = httpClient.execute(new HttpGet(url));
if(response.getStatusLine().getStatusCode()==302){
// 跳转的目标地址是在 HTTP-HEAD 中的
Header header = response.getFirstHeader("location");
// 这就是跳转后的地址
newUrl = header.getValue();
}
}catch(Exception e){
return WebResponse.resFail("异常信息",e);
}
从http-head中提取出重定向后的url就好了。