How to post request with spring boot web-client for Form data for content type application/x-www-form-urlencoded

We can use BodyInserters.fromFormData for this purpose webClient client = WebClient.builder() .baseUrl(“SOME-BASE-URL”) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .build(); return client.post() .uri(“SOME-URI) .body(BodyInserters.fromFormData(“username”, “SOME-USERNAME”) .with(“password”, “SONE-PASSWORD”)) .retrieve() .bodyToFlux(SomeClass.class) .onErrorMap(e -> new MyException(“messahe”,e)) .blockLast();

How to set multiple headers at once in Spring WebClient?

If those headers change on a per request basis, you can use: webClient.get().uri(“/resource”).headers(httpHeaders -> { httpHeaders.setX(“”); httpHeaders.setY(“”); }); This doesn’t save much typing; so for the headers that don’t change from one request to another, you can set those as default headers while building the client: WebClient webClient = WebClient.builder().defaultHeader(“…”, “…”).build(); WebClient webClient = WebClient.builder().defaultHeaders(httpHeaders … Read more

Spring WebClient: How to stream large byte[] to file?

With recent stable Spring WebFlux (5.2.4.RELEASE as of writing): final WebClient client = WebClient.create(“https://example.com”); final Flux<DataBuffer> dataBufferFlux = client.get() .accept(MediaType.TEXT_HTML) .retrieve() .bodyToFlux(DataBuffer.class); // the magic happens here final Path path = FileSystems.getDefault().getPath(“target/example.html”); DataBufferUtils .write(dataBufferFlux, path, CREATE_NEW) .block(); // only block here if the rest of your code is synchronous For me the non-obvious part was … Read more

Spring boot Webclient’s retrieve vs exchange

Adding to @JArgente’s answer. According to the official documentation of the retrieve() method: Perform the HTTP request and retrieve the response body. … This method is a shortcut to using exchange() and decoding the response body through ClientResponse. and the exchange() method Perform the HTTP request and return a ClientResponse with the response status and … Read more