Motivation

The RestClient.Builder has a method that takes a parameter of type Consumer<HttpHeaders> to set the default headers.

val defaultHeaders = HttpHeaders().apply {
    contentType = MediaType.APPLICATION_JSON
    setBasicAuth("encodedCredentials")
}

val restClient = RestClient.builder()
    .baseUrl("https://spring.io")
    .defaultHeaders {
        defaultHeaders.forEach { headerName, headerValue -> it[headerName] = headerValue }
    }
    .build()

In addition to this, it would be nice to have an intuitive method to set HttpHeaders directly, just like the methods in the common builder pattern.

Modifications

  • Add new method to set default headers in RestClient
Builder defaultHeaders(HttpHeaders httpHeaders);

Result

val defaultHeaders = HttpHeaders().apply {
    contentType = MediaType.APPLICATION_JSON
    setBasicAuth("encodedCredentials")
}

val restClient = RestClient.builder()
    .baseUrl("https://spring.io")
    .defaultHeaders(defaultHeaders)
    .build()

Now we can now intuitively set our custom HttpHeaders as the default header.

Comment From: jasongeeit

There is one problem.

Comment From: snicoll

Thanks for the suggestion but we prefer to be in control over the HttpHeaders instance and offering a consumer or a way to set one header is a common pattern with WebClient and RestClient.

You can put all values using .addAll.

Comment From: doljae

Like you said, I didn't notice that we can use addAll() instead of iterating copy key-value to default header in RestClient.builer().

Thanks your detailed explanation @snicoll 🙂