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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM