【问题标题】:ResponseEntity does not accept return type "byte[]" but "ResponseEntity"ResponseEntity 不接受返回类型“byte[]”而是“ResponseEntity”
【发布时间】:2022-01-12 12:50:31
【问题描述】:

我正在尝试通过 REST 端点将数据从一台服务器发送到另一台服务器:

服务器 B 启动此请求:

String resource = "http://...";
ResponseEntity<byte[]> response = restTemplate.getForObject(resource, byte[].class, customerID);

服务器A收到请求并返回文件:

    ResponseEntity<byte[]> resp = new ResponseEntity<byte[]>(myByteArrayOutputStream.toByteArray(), HttpStatus.OK);
    return resp;

但我在 .getForObject 行收到错误:

Required Type: ResponseEntity[]
Provided: byte[]

显然我必须将语句更改为:

byte[] response = restTemplate.getForObject(resource, byte[].class, customerID);

或到

ResponseEntity<byte[]> response = restTemplate.getForObject(resource, ResponseEntity.class, customerID);

然后错误消失了,但我在响应中丢失了 HttpStatus.Ok 消息?这里的正确解决方案是什么?

【问题讨论】:

    标签: java spring spring-boot spring-mvc


    【解决方案1】:

    是的,getForObject 方法不提供对响应元数据(如标头和状态代码)的访问。如果您必须访问这些数据,请使用RestTemplate#getForEntity(url, responseType, uriVariables)

    RestTemplate#getForEntity 返回一个包装器 ResponseEntity&lt;T&gt;,因此您可以读取响应元数据并通过 getBody() 方法读取正文。

    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
    }
    

    【讨论】:

    • 啊,这是为我做的,谢谢!
    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2019-09-08
    • 2018-09-15
    • 1970-01-01
    • 2020-01-27
    • 2022-01-06
    相关资源
    最近更新 更多