Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new method to set default headers in RestClient #32814

Closed
wants to merge 1 commit into from

Conversation

doljae
Copy link

@doljae doljae commented May 14, 2024

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.

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label May 14, 2024
@skystarxtogether
Copy link

There is one problem.

@snicoll
Copy link
Member

snicoll commented May 20, 2024

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.

@snicoll snicoll closed this May 20, 2024
@snicoll snicoll added status: declined A suggestion or change that we don't feel we should currently apply and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels May 20, 2024
@doljae
Copy link
Author

doljae commented May 22, 2024

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 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: declined A suggestion or change that we don't feel we should currently apply
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants