在`ResponseEntity`中返回错误格式的Spring响应。

huangapple go评论78阅读模式
英文:

Spring Return error format in ResponseEntity

问题

我尝试使用ResponseEntity来返回byte[]对象

    return new ResponseEntity<byte[]>(new Response(ResultCode.SUCCESS, SUCCESS).setResult(dataObj), HttpStatus.OK);

但是我得到了这样的响应:
[![enter image description here][1]][1]


另一种方式是我尝试直接返回byte[]对象

    return dataObj;

响应如下:
[![enter image description here][2]][2]

为什么会有不同?我能否像第二张图片那样返回带有数据的ResponseEntity?
英文:

I try to return the byte[] object by using ResponseEntity

return new ResponseEntity&lt;&gt;(new Response(ResultCode.SUCCESS, SUCCESS).setResult(dataObj), HttpStatus.OK);

but and got a response like that:
在`ResponseEntity`中返回错误格式的Spring响应。

and another way I try to return the direct byte[] object

return dataObj;

the response like that:
在`ResponseEntity`中返回错误格式的Spring响应。

Why do we have different? and Can I return the ResponseEntity with data like the 2nd image?

答案1

得分: 0

尝试以下代码。访问此API时,它将以响应的方式发送图像本身。

@GetMapping(value = "/image/{id}")
public ResponseEntity<?> getImageById(@PathParam Long id) throws Exception {
  String imageData = this.entityRepository.findById(id).orElse(null).getData();
  byte[] imageByte = Base64.getDecoder().decode(new String(imageData).getBytes("UTF-8"));
  MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(mediaType);
  return new ResponseEntity<>(imageByte, headers, HttpStatus.OK);
}
英文:

Try following code. It will send image itself in response on accessing this API.

@GetMapping(value = &quot;/image/{id}&quot;)
public ResponseEntity&lt;?&gt; getImageById(@PathParam Long id) throws Exception {
  String imageData = this.entityRepository.findById(id).orElse(null).getData();
  byte[] imageByte = Base64.getDecoder().decode(new String(imageData).getBytes(&quot;UTF-8&quot;));
  MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(mediaType);
  return new ResponseEntity&lt;&gt;(imageByte, headers, HttpStatus.OK);
}

huangapple
  • 本文由 发表于 2020年10月12日 16:51:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64314557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定