Spring RestTemplate redirect 302

 

The redirection is followed automatically if the request is a GET request (see this answer). To make it happen on POST requests, one option might be to use a different request factory, like HttpComponentsClientHttpRequestFactory, and set it to use an HttpClient with the required settings to follow the redirect (see LaxRedirectStrategy):

final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
                                               .setRedirectStrategy(new LaxRedirectStrategy())
                                               .build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);

I haven't tested, but this should work.
https://stackoverflow.com/questions/32392634/spring-resttemplate-redirect-302

Spring的RestTemplate自动重定向,如何拿到重定向后的地址?

第一种解决方案

既然知道了spring会设置自动重定向,那么要禁止自动重定向就很简单了。我们写一个类来继承SimpleClientHttpRequestFactory,然后复写prepareConnection方法,把该属性设置为false即可,代码如下:

public class NoRedirectSimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        super.prepareConnection(connection, httpMethod);
        connection.setInstanceFollowRedirects(false);
    }
}

那么该如何在创建的时候使用这个ClientHttpRequestFactory 呢,一种简单的方法直接在创建RestTemplate的时候传入参数即可

    private static final RestTemplate REST_TEMPLATE = new RestTemplate(new NoRedirectSimpleClientHttpRequestFactory());

这样的话就返回的结果就是302了,可以在header中的"Location"拿到重定向的地址,再使用另外的RestTemplate来请求下载就可以了。但是spring既然提供了功能强大的RestTemplateBuilder,我们就要学会使用它,如下,可以顺便设置下超时时间之类的属性:

    private static final RestTemplate REST_TEMPLATE = new RestTemplateBuilder()
            .requestFactory(NoRedirectSimpleClientHttpRequestFactory.class)
            .setConnectTimeout(Duration.ofMillis(3000))
            .setConnectTimeout(Duration.ofMillis(5000))
            .build();

https://blog.csdn.net/m0_37657841/article/details/107391699

 

 

feign 怎么处理302的响应?【测试未通过,copy过来留一个思路】

1.如果直接使用Feign,可以通过修改Options来实现是否自动跳转,默认是true,也就是自动重定向。

Request.Options customerOptions = new Request.Options(10_000, 20_000, false);
Feign.builder().options(customerOptions).build();

2.如果使用Spring的open-feign,则可以通过修改配置文件来实现。

feign:
  httpclient:
    follow-redirects: false

https://segmentfault.com/q/1010000014239099

 

 https://wenku.csdn.net/answer/e54f3d1b7a9a4a40a04ee4150811ff8b

 

posted @ 2024-01-23 11:40  沧海一滴  阅读(434)  评论(0编辑  收藏  举报