无法让TestRestTemplate不自动跟随302重定向的问题排查
TestRestTemplate无法阻止自动跟随302重定向的问题解决
一、为什么TestRestTemplate未按文档描述工作?
- 依赖版本不兼容:Spring Boot 3.x及以上版本,TestRestTemplate的自动配置逻辑已切换为适配Apache HttpClient 5.x,你添加的4.3.6属于旧版本,自动配置类(如
HttpClientAutoConfiguration)只会识别5.x版本的依赖,旧版本无法触发禁用重定向的逻辑。 - 默认使用JDK原生客户端:如果类路径中没有适配的HttpClient,Spring Boot会默认采用JDK自带的
SimpleClientHttpRequestFactory,该客户端默认开启重定向跟随,不会自动禁用。
二、可行的配置方法
方法1:更换为兼容的Apache HttpClient 5.x依赖
修改build.gradle中的依赖,替换为HttpClient 5.x版本,Spring Boot自动配置会识别并默认禁用重定向:
testImplementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'
替换原有的org.apache.httpcomponents:httpclient:4.3.6,重新运行测试后即可获取原始302响应。
方法2:手动配置TestRestTemplate禁用重定向
方式A:基于JDK原生客户端配置
在测试类中手动创建禁用重定向的SimpleClientHttpRequestFactory,并构建自定义TestRestTemplate:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class redirectTest { @Test void redirectTest() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setFollowRedirects(false); TestRestTemplate customRestTemplate = new TestRestTemplate(requestFactory); var response = customRestTemplate.getForEntity("/redirect", String.class); System.out.println("Response: " + response.getBody()); assertEquals(302, response.getStatusCode().value()); } }
方式B:基于Apache HttpClient 4.x配置
若坚持使用HttpClient 4.x,可手动构建禁用重定向的HttpClient实例:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class redirectTest { @Test void redirectTest() { CloseableHttpClient httpClient = HttpClientBuilder.create() .disableRedirectHandling() .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); TestRestTemplate customRestTemplate = new TestRestTemplate(requestFactory); var response = customRestTemplate.getForEntity("/redirect", String.class); System.out.println("Response: " + response.getBody()); assertEquals(302, response.getStatusCode().value()); } }
方法3:全局配置自定义TestRestTemplate
创建测试配置类,全局定义禁用重定向的TestRestTemplate Bean,供多个测试类复用:
@TestConfiguration public class TestRestTemplateConfig { @Bean public TestRestTemplate testRestTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setFollowRedirects(false); return new TestRestTemplate(requestFactory); } }
在测试类中导入该配置:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Import(TestRestTemplateConfig.class) public class redirectTest { @Autowired TestRestTemplate rest; @Test void redirectTest() { var response = rest.getForEntity("/redirect", String.class); System.out.println("Response: " + response.getBody()); assertEquals(302, response.getStatusCode().value()); } }
内容的提问来源于stack exchange,提问作者Holden Karl Hain
相关产品推荐
相关产品推荐

