【问题标题】:How can I disable spring resttemplate redirect when getting stuff?获取东西时如何禁用spring resttemplate重定向?
【发布时间】:2019-06-18 06:51:16
【问题描述】:

我正在与一个古老的服务集成,当我调用它时,它会用 jsessionid 重写 url。我正在使用 resttemplate 与服务交谈,问题是它永远遵循重定向,因为我没有设置 jsession cookie。

我想在 spring resttemplate 中关闭以下重定向。

【问题讨论】:

    标签: spring resttemplate


    【解决方案1】:

    我想出了一种方法,不知道这是否是首选方法。

    @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); CloseableHttpClient build = HttpClientBuilder.create().disableRedirectHandling().build(); factory.setHttpClient(build); restTemplate.setRequestFactory(factory); return restTemplate; }

    【讨论】:

      【解决方案2】:

      您还可以编写自己的 HttpRequestFactory 类并覆盖默认行为:

      class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
          @Override
          protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
              super.prepareConnection(connection, httpMethod);
              connection.setInstanceFollowRedirects(false);
          }
      }
      
      @Configuration
      public class AppConfig {
      
          @Bean
          public RestTemplate httpClient(RestTemplateBuilder builder) {
              return builder
                      .setConnectTimeout(Duration.ofSeconds(10))
                      .setReadTimeout(Duration.ofSeconds(10))
                      .requestFactory(CustomClientHttpRequestFactory.class)
                      .build();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2016-12-11
        • 2015-11-30
        • 2016-08-29
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 2017-12-14
        • 2015-06-25
        相关资源
        最近更新 更多