本文转自:http://wiyi.org/binary-to-string.htmlhtml
json 是一种很简洁的协议,但惋惜的是,它只能传递基本的数型(int,long,string等),但不能传递byte类型。若是想要传输图片等二进制文件的话,是没办法直接传输。java
本文提供一种思路给你们参考,让你们能够在json传输二进制文件,若是你们有这个需求又不知怎么实现的话,也许本文可以帮到你。思想适用于全部语言,本文以java实现,相信你们很容易就能转化为本身懂得语言。算法
思路
1. 读取二进制文件到内存json
2. 用Gzip压缩一下。毕竟是在网络传输嘛,固然你也能够不压缩。数组
3. 用Base64 把byte[] 转成字符串服务器
补充:什么是Base64
如下摘自阮一峰博客,Base64的具体编码方式,你们能够直接进入。网络
Base64是一种编码方式,它能够将8位的非英语字符转化为7位的ASCII字符。这样的初衷,是为了知足电子邮件中不能直接使用非ASCII码字符的规定,可是也有其余重要的意义:编码
a)全部的二进制文件,均可以所以转化为可打印的文本编码,使用文本软件进行编辑;加密
b)可以对文本进行简单的加密。spa
实现
主要思路就是以上3步,把字符串添加到json字段后发给服务端,而后服务器再用Base64解密–>Gzip解压,就能获得原始的二进制文件了。是否是很简单呢?说了很多,下面咱们来看看具体的代码实现。
***注:Java SE是没办法直接用Base64的哦,必需要先本身去下载一份。但Android已经集成了Base64,所以你们能够直接在Android使用。
- public class TestBase64 {
- public static void main(String[] args) {
- byte[] data = compress(loadFile());
-
- String json = new String(Base64.encodeBase64(data));
- System.out.println("data length:" + json.length());
- }
-
-
- public static byte[] loadFile() {
- File file = new File("d:/11.jpg");
-
- FileInputStream fis = null;
- ByteArrayOutputStream baos = null;
- byte[] data = null ;
-
- try {
- fis = new FileInputStream(file);
- baos = new ByteArrayOutputStream((int) file.length());
-
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = fis.read(buffer)) != -1) {
- baos.write(buffer, 0, len);
- }
-
- data = baos.toByteArray() ;
-
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (fis != null) {
- fis.close();
- fis = null;
- }
-
- baos.close() ;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return data ;
- }
-
-
- public static byte[] compress(byte[] data) {
- System.out.println("before:" + data.length);
-
- GZIPOutputStream gzip = null ;
- ByteArrayOutputStream baos = null ;
- byte[] newData = null ;
-
- try {
- baos = new ByteArrayOutputStream() ;
- gzip = new GZIPOutputStream(baos);
-
- gzip.write(data);
- gzip.finish();
- gzip.flush();
-
- newData = baos.toByteArray() ;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- gzip.close();
- baos.close() ;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- System.out.println("after:" + newData.length);
- return newData ;
- }
- }
最后输出了一下字符串长度,你们也许以为通过压缩也没下降多少体积嘛。但你们能够试试不用gzip,你会发现通过转换的字符串比原来大多了。没办法,这是由Base64的算法决定的。因此嘛,仍是压缩一下好。
本文所使用的方法比较简单,你们若是有更好或者以为有更好的方式,不妨一块儿探讨一下。
最后顺便吐槽一下Java,居然写了这么多行代码。要是用Python,估计没几行就能搞定了。