Default RestClient
does not follow redirect (in case of 301 at least.
Response body is null
@RestController
class SampleController {
@GetMapping("/first")
fun redirectToSecond() = ResponseEntity
.status(301)
.header("Location", "/second")
.build<Unit>()
@GetMapping("/second")
fun noRedirect() = "OK"
}
@Component
class Runner(
@Value("\${server.port}")
private val port: Int
) : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
// this works: redirect is followed
val entityWithRC = RestClient.builder(RestTemplate()) // <---- this
.baseUrl("http://localhost:$port")
.build()
.get()
.uri("/first")
.retrieve()
.toEntity<String>()
// this does not work: redirect is not followed
val entityWithDefaults = RestClient.builder()
.baseUrl("http://localhost:$port")
.build()
.get()
.uri("/first")
.retrieve()
.toEntity<String>()
println(entityWithRC)
println(entityWithDefaults)
}
}
````
Console output:
<200 OK OK,OK,[Content-Type:"text/plain;charset=UTF-8", Content-Length:"2", Date:"Thu, 17 Oct 2024 14:39:00 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]> <301 MOVED_PERMANENTLY Moved Permanently,[content-length:"0", date:"Thu, 17 Oct 2024 14:39:00 GMT", location:"/second"]>
**Comment From: bclozel**
Thanks for getting in touch. This behavior is by design.
`RestTemplate` will use by default the `SimpleClientHttpRequestFactory` (backed by `java.net.HttpURLConnection`), while the more recent `RestClient` is using by default the `JdkClientHttpRequestFactory` (backed by `java.net.http.HttpClient`).
In this case, `java.net.HttpURLConnection` and `java.net.http.HttpClient` have different behavior when it comes to following redirects. As a framework, our best option is to rely as much as possible on the clients defaults and not try to align all clients on a single behavior (it's impossible and it would be surprising to many).
You can get the behavior you want by configuring the request factory like this:
```java
HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build();
RestClient restClient = RestClient.builder().requestFactory(new JdkClientHttpRequestFactory(httpClient)).build();