java RESTful Web 服务中的字节数组与 Base 64 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4853886/
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
Byte array versus Base 64 string in RESTful web service
提问by Jaguar
My REST web service has to send an image file to the client. I am confused between 2 options : send the image as a byte array, or should I encode it as a base 64 string ? What are the pros and cons of each ? I may have to compress the image using gzip...should it create problem with any one of methods ? I may even need to expose my method as a SOAP service, which method should I prefer in that case ?
我的 REST Web 服务必须向客户端发送图像文件。我对 2 个选项感到困惑:将图像作为字节数组发送,还是应该将其编码为 base 64 字符串?各自的优缺点是什么?我可能必须使用 gzip 压缩图像...是否应该使用任何一种方法产生问题?我什至可能需要将我的方法公开为 SOAP 服务,在这种情况下我应该更喜欢哪种方法?
Thanks !!
谢谢 !!
回答by dkarp
The wonderful thing about a RESTful interface is that it's just HTTP. So if you expose the "byte array" version via REST, any browser can do an HTTP GET
on your REST URL and receive and directly renderyour image. Returning the payload verbatim is far more RESTful than placing an encoding on it. There is not much to recommend an extra base64 encoding layer via REST.
RESTful 接口的美妙之处在于它只是 HTTP。因此,如果您通过 REST 公开“字节数组”版本,则任何浏览器都可以GET
在您的 REST URL 上执行 HTTP并接收并直接呈现您的图像。逐字返回有效负载远比在其上放置编码更具有 RESTful 风格。通过 REST 推荐一个额外的 base64 编码层并不多。
If you're returning SOAP, you absolutely want to return a base64 string. Raw binary data is not compatible with XML, upon which SOAP is built. You can try to work around it via MTOM, but for general-purpose compatibility with SOAP clients you probably want inlined base64-encoded data.
如果您要返回 SOAP,您绝对希望返回一个 base64 字符串。原始二进制数据与构建 SOAP 的 XML 不兼容。您可以尝试通过MTOM解决它,但为了与 SOAP 客户端的通用兼容性,您可能需要内联的 base64 编码数据。
In general, there's no benefit to be gained by compressing an image file. The image formats themselves internally involve compression, and a second compression pass will not gain any more space savings.
一般来说,压缩图像文件没有任何好处。图像格式本身在内部涉及压缩,第二次压缩不会节省更多空间。
回答by tenshi
If your service returnes JSON or XML (image + some information), than you should encode image in base 64 because both of them string based, and you want to transfer byte array. The only question, whether you should make it yourself or it should be made my framework you use.
如果您的服务返回 JSON 或 XML(图像 + 一些信息),那么您应该以 base 64 编码图像,因为它们都是基于字符串的,并且您想要传输字节数组。唯一的问题是,您应该自己制作还是应该将其制作为您使用的我的框架。
Situation with GZip is clear - relay compression to the servlet container (like tomcat - you can configure, whether response should be gzipped). Alternatively you can use something like GZipFilter
.
GZip 的情况很清楚 - 将压缩中继到 servlet 容器(如 tomcat - 您可以配置,是否应 gzipped 响应)。或者,您可以使用类似GZipFilter
.