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>
    
  • 相关阅读:
    +7白盒测试与黑盒测试的定义与区别
    对于逆序数组,,选择排序 和 插入排序 那个更快?
    +1.1向量 链表 数组
    3.2 二十三种设计模式全解析
    3.1软件体系结构风格
    Mysql: 强制走索引:mysql between 日期索引 索引问题-日期索引使用
    php: xampp安装对应的phalcon版本(3.2.2-php5.6):比如redis-php5.6, php_igbinary-5.6
    京东自营,你TM太坑了。
    php:微信公众平台上传多媒体接口 41005错误
    php:如何使用PHP排序, key为字母+数字的数组(多维数组)
  • 原文地址:https://www.cnblogs.com/cnsyear/p/13814772.html
Copyright © 2011-2022 走看看