默认DefaultRedirectStrategy只会重定向 GET与HEAD请求, POST等请求不会自动重定向
LaxRedirectStrategy会进行重定向,但是无法解析获取请求链路
// 扩展LaxRedirectStrategy,记录最终访问的Uri与重定向链路
@Slf4j
public class AdvanceLaxRedirectStrategy extends LaxRedirectStrategy {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
boolean redirected = super.isRedirected(request, response, context);
Header[] allHeaders = response.getAllHeaders();
Set<String> uris = new LinkedHashSet<>();
for (Header header : allHeaders) {
if (StringUtils.equals(header.getName(), "Location")) {
context.setAttribute("uri", header.getValue());
}
}
if (context.getAttribute("uris") != null) {
uris.addAll(Arrays.asList(context.getAttribute("uris").toString().split(";")));
}
Object uri = context.getAttribute("uri");
if (uri != null) {
response.setHeader("uri", String.valueOf(uri));
uris.add(String.valueOf(uri));
}
if (!uris.isEmpty()) {
context.setAttribute("uris", String.join(";", uris));
response.setHeader("uris", String.join(";", uris));
}
return redirected;
}
}
// 使用自定义重定向
private static final RestTemplate restTemplate = new RestTemplateBuilder()
.requestFactory(() -> new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder.create().useSystemProperties().setRedirectStrategy(new AdvanceLaxRedirectStrategy()).build()))
.build();
// 获取最终访问的uri
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
String actualUrl = Optional.ofNullable(entity.getHeaders().getFirst("uri")).orElse(url);