Created
March 15, 2019 10:40
-
-
Save svenakela/7978c186ed88be9435f152be15a9099d to your computer and use it in GitHub Desktop.
Get the content length of a body and add it the CONTENT_LENGTH header with Spring's Reactive WebClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.charset.StandardCharsets; | |
import org.junit.Assert; | |
import org.junit.Test; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.web.reactive.function.BodyInserters; | |
import org.springframework.web.reactive.function.client.WebClient; | |
import reactor.core.publisher.Mono; | |
public class BodyContentLenghtTest { | |
@Test | |
public void postWithContentLength() { | |
final Mono<String> mono = Mono.just("HELLO WORLDZ"); | |
final String response = WebClient.create("http://httpbin.org") | |
.post() | |
.uri("/post") | |
.header(HttpHeaders.CONTENT_LENGTH, mono.map(s -> String.valueOf(s.getBytes(StandardCharsets.UTF_8) | |
.length)) | |
.block()) | |
.body(BodyInserters.fromPublisher(mono, String.class)) | |
.retrieve() | |
.bodyToMono(String.class) | |
.log() | |
.block(); | |
Assert.assertTrue(response.contains("\"Content-Length\": \"12\"")); | |
} | |
@Test | |
public void postFlatMapTheBody() { | |
final Mono<String> mono = Mono.just("HELLO WORLDZZ") | |
.flatMap(body -> WebClient.create("http://httpbin.org") | |
.post() | |
.uri("/post") | |
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.getBytes(StandardCharsets.UTF_8).length)) | |
.syncBody(body) | |
.retrieve() | |
.bodyToMono(String.class)) | |
.log(); | |
Assert.assertTrue(mono.block().contains("\"Content-Length\": \"13\"")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment