java 字节的 Spring REST 模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40427052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring REST Template for Byte
提问by Tiny
I am fetching the byte array using spring framework rest template, But I also need to fetch the Mediatype of this byte .
我正在使用 spring 框架 rest 模板获取字节数组,但我还需要获取此字节的 Mediatype 。
The mediaType of this bytearray can be of any type.
此 bytearray 的 mediaType 可以是任何类型。
The code used now for fetching byte is below.
现在用于获取字节的代码如下。
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.valueOf("application/pdf")));
ResponseEntity<byte[]> result = restTemp.exchange(url, HttpMethod.GET, entity, byte[].class,documentId);
The above code will fetch only pdf content type.
上面的代码将只获取 pdf 内容类型。
How to set the contentType to accept any generic MediaType because the service at the other end is providing any random MediaType for the byteArray.
如何设置 contentType 以接受任何通用 MediaType,因为另一端的服务正在为 byteArray 提供任何随机 MediaType。
Could someone please suggest how the MediaType can be fetched.
有人可以建议如何获取 MediaType。
Any suggestions are welcome..
欢迎任何建议..
回答by pedrofb
Just not send the accept
header to not force the server to return that content-type
. This is the same as sending a wildcard */*
只是不发送accept
标头以不强制服务器返回该标头content-type
。这与发送通配符相同*/*
//HttpHeaders headers = new HttpHeaders();
//headers.setAccept(Collections.singletonList(MediaType.WILDCARD));
ResponseEntity<byte[]> result = restTemp.exchange(url, HttpMethod.GET, entity, byte[].class,documentId);
After this, extract the content-type
from the headers of the response
在此之后,content-type
从响应的标头中提取
byte body[] = result.getBody();
MediaType contentType = result.getHeaders().getContentType();
回答by toootooo
You can store a media type in the HTTP headers and use - ResponseEntity.getHeaders(), for instance. or you can wrap byte array and media type into holder class.
例如,您可以在 HTTP 标头中存储媒体类型并使用 - ResponseEntity.getHeaders()。或者您可以将字节数组和媒体类型包装到持有者类中。
回答by Andy W
MediaType mediaType = result.getHeaders().getContentType();
MediaType mediaType = result.getHeaders().getContentType();