简体   繁体   中英

ResponseEntity does not accept return type "byte[]" but "ResponseEntity"

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM