解决RestTemplate请求url出现301转发错误 301 Moved Permanently

解决RestTemplate请求url出现301转发错误 301 Moved Permanently

使用restTemplate.getForObject方法访问url 提示301错误

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<h1>301 Moved Permanently</h1>
<p>The requested resource has been assigned a new permanent URI.</p>
<hr/>Powered by Tengine/1.5.2</body>
</html>

但是这个url使用浏览器和postman都是可以正常访问的,由此可以判断是restTemplat配置有问题。

默认RestTemplate使用的是SimpleClientHttpRequestFactory工厂。追踪可见,默认它是以java.net下的HttpURLConnection方式发起的请求,所以RestTemplate是支持自定义其他方式发起请求的。

解决方法

使用HttpClient实现请求自动转发需要创建HttpClient时设置重定向策略。

// 该地址有301转发,为了不影响其他的地方,这里使用自定义的restTemplate。
// 实现请求自动转发需要创建HttpClient时设置重定向策略。
// 生产环境使用系统代理,由于使用的是HttpClient工厂 代理也需要使用HttpClient的代理模式
RestTemplate restTemplate = new RestTemplate();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
HttpClient httpClient;
if (AntdConstant.ENV_PROD.equals(profiles)) {
    HttpHost proxy = new HttpHost(antdProperties.getProxy().getIp(), antdProperties.getProxy().getPort());
    httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).setProxy(proxy).build();
} else {
    httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
}
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
String result = restTemplate.getForObject(url, String.class);
<!--HttpClient-->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
原文地址:https://www.cnblogs.com/cnsyear/p/13814772.html