spring-projects / spring-boot

Spring Boot helps you to create Spring-powered, production-grade applications and services with absolute minimum fuss.
https://spring.io/projects/spring-boot
Apache License 2.0
75.39k stars 40.74k forks source link

Disable redirects by default in TestRestTemplate for all HTTP clients #27360

Open quaff opened 3 years ago

quaff commented 3 years ago

My test is broken after rest-assured dependency removed, I found it caused by TestRestTemplate inconsistent follow redirects. TestRestTemplate will use apache httpclient since org.apache.httpcomponents: httpclient is introduced by rest-assured, following redirects is disabled by default, thanks to https://github.com/spring-projects/spring-boot/issues/1497, you can enable it by passing HttpClientOption.ENABLE_REDIRECTS. If apache httpclient is not present, TestRestTemplate will fallback to okhttp3: https://github.com/spring-projects/spring-boot/blob/47516b50c39bd6ea924a1f6720ce6d4a71088651/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySupplier.java#L41-L45

okhttp3 enable following redirects by default, I think TestRestTemplate should keep same behavior not matter which underlying implementation, disabling following redirects is sensible since test want to know which url is redirected to, and it would be better if this option can be mutated.

quaff commented 3 years ago
Implementation Default
HttpComponentsClientHttpRequestFactory false
OkHttp3ClientHttpRequestFactory true
SimpleClientHttpRequestFactory true
wilkinsona commented 3 years ago

Thanks for the suggestion. As described in the javadoc, the current behaviour is expected:

If Apache Http Client 4.3.2 or better is available (recommended) it will be used as the client, and by default configured to ignore cookies and redirects.

We can explore the possibility of doing the same for other clients.

quaff commented 3 years ago

Or provide a mutate method withFollowRedirects like withBasicAuth for TestRestTemplate.

quaff commented 1 week ago

@philwebb TestRestTemplate use FOLLOW_WHEN_POSSIBLE since 3.4.0, it breaks tests that rely on DONT_FOLLOW.

EDIT: it's caused by followRedirects of jdk.internal.net.http.HttpClientImpl changed from NEVER to NORMAL after upgrading to 3.4.0.