Reputation: 37
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 ?
Upvotes: 2
Views: 324