1. 程式人生 > 實用技巧 >解決RestTemplate請求url出現301轉發錯誤 301 Moved Permanently

解決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>