【问题标题】:Spring RestTemplate follow redirect with cookieSpring RestTemplate 使用 cookie 跟随重定向
【发布时间】:2016-08-29 17:07:04
【问题描述】:

最近我遇到了一个问题,我需要向远程服务发出 GET 请求(我假设使用一个简单的 servlet),而 RestTemplate 返回了 Too many redirects!

经过一番调查,似乎对指定远程服务的第一个请求实际上只是一个带有一些 Set-Cookie 标头的 302 重定向(对自身)。如果我使用的是“普通”浏览器,它会确认标头,正确设置 cookie,然后按照应该满足正常 200 响应的重定向。

我发现 RestTemplate 不接受 Set-Cookie 标头,因此会一遍又一遍地进行重定向。

有什么方法可以让 RestTemplate 仅针对当前请求确认 Set-Cookie 标头?我最好不希望它保持状态,因为系统的其他部分也使用了 RestTemplate。

问候

【问题讨论】:

  • this 是你想做的吗?还有this one ?
  • @ha9u63ar Botht links 将 cookie 添加到请求标头。我最好不想提出 2 个单独的请求。 (1 用于首先在重定向处停止,嗅探“Set-Cookie”标头,将其添加到第二个请求并执行该请求)我希望 RestTemplate 遵循重定向(它实际上已经这样做了),同时还确认“Set- Cookie”标头。

标签: java spring rest integration resttemplate


【解决方案1】:

我确实以不同于 Michal Foksa 的方式解决了这个问题。 (在他回答之前)

解决它的一种方法是实现一个线程本地cookiemanager,并将其设置为系统默认值。这将使 RestTemplate 使用 cookiemanager 存储 cookie,并在请求线程死亡后释放 cookiemanager。

问候

【讨论】:

    【解决方案2】:

    最好使用最新版本的httpclient。默认情况下,spring rest 模板不允许设置标题。

    【讨论】:

      【解决方案3】:

      Spring 默认请求工厂 (SimpleClientHttpRequestFactory) 不处理 cookie。将其替换为具有 Apache HttpClient 的请求工厂,它能够使用 cookie:

      import org.apache.http.impl.client.CloseableHttpClient;
      import org.apache.http.impl.client.HttpClientBuilder;
      import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
      import org.springframework.web.client.RestTemplate;
      
      CloseableHttpClient httpClient = HttpClientBuilder
          .create()
          .build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
      RestTemplate restTemplate = new RestTemplate(factory);
      

      【讨论】:

        猜你喜欢
        • 2015-11-30
        • 2015-09-24
        • 2015-06-07
        • 2010-09-26
        • 2012-01-05
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        相关资源
        最近更新 更多