2

I want to use the Spring Boot's RestClient feature for my application.

So, I want to migrate the existing Spring Boot's RestTemplate code to Spring Boot's RestClient code.

I have a code that works using RestTemplate:

private byte[] request(Data data) {
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_JSON);
   HttpEntity<ResponseData> entity = new HttpEntity<>(data, headers);
   return restTemplate.exchange(url + uri, HttpMethod.POST, entity, byte[].class).getBody();
}

How can I write equivalent request using Spring Boot's RestClient?

I've tried this:

    private byte[] request(Data data) {
        return restClientBuilder.baseUrl(url)
                .build()
                .post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(data)
                .retrieve()
                .onStatus(HttpStatusCode::isError, new ApiErrorHandler())
                .toEntity(byte[].class).getBody();
    }

This:

    private byte[] request(Data data) {
        return restClientBuilder.baseUrl(url)
                .build()
                .post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(data)
                .retrieve()
                .onStatus(HttpStatusCode::isError, new ApiErrorHandler())
                .body(byte[].class);
    }

This

    private byte[] request(Data data) {
        return restClientBuilder.baseUrl(url)
                .build()
                .post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(data)
                .exchange((request, res) -> res.getBody().readAllBytes());
    }


And this way


    private byte[] requestD(Data data) {
        return restClientBuilder.baseUrl(url)
                .build()
                .post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(data)
                .retrieve()
                .onStatus(HttpStatusCode::isError, new ApiErrorHandler())
                .toEntity(new ParameterizedTypeReference<byte[]>() {
                }).getBody();
    }

And none of these works. Can you help me please ?

1
  • 3
    What do you mean by "not work"? Do you get compilation error? Runtime exception? Wrong result? Commented Aug 14, 2024 at 4:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.