背景:
最近,用RestTemplate访问某个重定向地址,即302、301跳转后的uri,但是spring的RestTemplate提供的get方法会默认自动重定向,返回的即为200,因此需要取消自动重定向或者在重定向过程中拿到真正的uri。
解决方法:
方法1:
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
方法2:
既然spring会设置自动重定向,那么要禁止自动重定向就很简单了。
我们写一个类来继承SimpleClientHttpRequestFactory,然后复写prepareConnection方法,把该属性设置为false即可,代码如下:
public class NoRedirectSimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
}
}
最后是bean配置:
class="com.dianping.ba.crm.mobile.utils.NoRedirectClientHttpRequestFactory">
注入你自己的ClientHttpRequestFactory就行了!这里也可以设置连接时间和超时时间。
参考:
Spring的RestTemplate自动重定向,如何拿到重定向后的地址?_KiroScarlet的博客-CSDN博客_resttemplate 重定向