I'm trying to send a request using Spring Webflux's WebClient including multiple cookies. My code looks like this:
Mono<Void> loginCall = webClient.post()
.uri("/Sites/Login")
.cookie("key1", "value1")
.cookie("key2", "value2")
.cookie("key3", "value3")
.exchange()
.flatMap(clientResponse -> clientResponse.bodyToMono(Void.class));
What I receive on my endpoint looks like this (note the multiple cookie headers):
$ nc -l -p 8989
POST /Sites/Login HTTP/1.1
user-agent: ReactorNetty/0.8.11.RELEASE
host: localhost:8989
accept: */*
transfer-encoding: chunked
cookie: key1=value1
cookie: key2=value2
cookie: key3=value3
My expectation is to receive a HTTP request like this (a single cookie header):
cookie: key1=value1; key2=value2; key3=value3
I'm using Spring Boot 2.1.8.
I've tried numerous ways but everything I tried results in multiple cookie headers. The HTTP specification is quite clear about the fact that multiple cookie headers must not be used (and my web server receiving this request doesn't like it either).
How do I add multiple cookies to a WebClient request so that they are merged into a single HTTP header? (Yes, I can start setting the header manually and merge the cookies, but this somehow feels wrong)
From this article on SitePoint: If multiple cookies of the same name match a given request URI, one is chosen by the browser. The more specific the path, the higher the precedence. However precedence based on other attributes, including the domain, is unspecified, and may vary between browsers.
When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field. It looks like the use of multiple Cookie headers is, in fact, prohibited!
To set the custom header to each response, use addHeader() method of the HttpServletResponse interface. That's all about setting a header to all responses in Spring Boot.
As explained in the Spring Boot reference documentation, Spring Boot will auto-configure a Spring MVC application if both MVC and WebFlux are available.
Had the same problem, the only way I found was to produce the 'Cookie' header manually like this (Groovy language):
UserInfo retrieveUserInfo(List<Cookie> cookies) {
String cookieHeader = cookies.collect { "${it.name}=${it.value}" }.join('; ')
return webClient
.get()
.uri('your API path here')
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.COOKIE, cookieHeader)
.retrieve()
.bodyToMono(UserInfo.class)
.block()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With