zoukankan      html  css  js  c++  java
  • 解决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>
    
  • 相关阅读:
    【JavaWeb项目】一个众筹网站的开发(四)后台用户注册功能
    【JavaWeb项目】一个众筹网站的开发(三)第一个网页
    【JavaWeb项目】一个众筹网站的开发(二)架构搭建之架构测试
    【JavaWeb项目】一个众筹网站的开发(一)架构搭建
    Eclipse安装SVN插件方式简明介绍
    Struts&nbsp;result&nbsp;param详细设置
    第三次寒假作业
    寒假作业二
    我的寒假C(C++)学习计划
    1001. A+B Format (20)的解题思路以及多源代码文件的尝试编写
  • 原文地址:https://www.cnblogs.com/cnsyear/p/13814772.html
Copyright © 2011-2022 走看看