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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:12:29  来源:igfitidea点击:

Spring REST Template for Byte

javaspringcxfspring-rest

提问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 acceptheader 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-typefrom 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();

回答by developer

You can set the MediaTypeas application/octet-stream, look at here

你可以设置MediaTypeapplication/octet-stream,看这里