Reputation: 753
I am trying to send data from one server to another one via REST endpoint:
Server B starts this request:
String resource = "http://...";
ResponseEntity<byte[]> response = restTemplate.getForObject(resource, byte[].class, customerID);
Server A receives the request and returns the file:
ResponseEntity<byte[]> resp = new ResponseEntity<byte[]>(myByteArrayOutputStream.toByteArray(), HttpStatus.OK);
return resp;
But I get an error at the .getForObject line:
Required Type: ResponseEntity[]
Provided: byte[]
So obviously I would have to change the statement to:
byte[] response = restTemplate.getForObject(resource, byte[].class, customerID);
or to
ResponseEntity<byte[]> response = restTemplate.getForObject(resource, ResponseEntity.class, customerID);
Then the error is gone but I lose the HttpStatus.Ok message at the response? What would be the proper solution here?
Upvotes: 0
Views: 2112
Reputation: 3370
Yes, the getForObject
method does not provide access to response metadata like headers and the status code. If you have to access this data, then use RestTemplate#getForEntity(url, responseType, uriVariables)
The RestTemplate#getForEntity
returns a wrapper ResponseEntity<T>
so you can read the response metadata and also read the body through the getBody()
method.
ResponseEntity<byte[]> response = restTemplate.getForEntity(resource, byte[].class, customerID);
if (response.getStatusCode() == HttpStatus.OK) {
byte[] responseContent = response.getBody();
// ...
} else {
// this is not very useful because for error codes (4xx and 5xx) the RestTemplate throws an Exception
}
Upvotes: 1