使用RestTemplate时如何处理跟随跳转(HTTP 302

2018-07-24  本文已影响0人  FFJ

在使用RestTemplate请求服务端,获取授权码时, 会经过两次的 HTTP 302 Found 跳转,开发者在实现时需要允许客户端跟随跳转。
解决办法来自Stack Overflow的一个问答:Spring RestTemplate redirect 302

相关代码:

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);

其中用到的HttpComponentsClientHttpRequestFactory、HttpClientBuilder、HttpClient等类,可以用maven来引入:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
上一篇 下一篇

猜你喜欢

热点阅读