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>
    
  • 相关阅读:
    怎样把顶级控件加在另一个控件上?
    GML规范相关资源
    VB6.0的事件、回调函数等
    [转]使用ErrorProvider改善用户体验
    今日新增3D词汇
    [转]在用数据绑定的时候我为什么不能把焦点移出(Tab out)我的控件?(译)
    [翻译]Windows Phone 7 Application Controls
    转帖Windows Phone 7开发环境搭建
    利用SDF2.3获取Windows Mobile上的IP地址和MAC地址
    “2010 GCR MVP Open Day”之行
  • 原文地址:https://www.cnblogs.com/cnsyear/p/13814772.html
Copyright © 2011-2022 走看看