json传输文件中的BASE64加密问题

1、用json传输图片一些注意事项

 json是一种轻量级的数据结构,我们知道json是以字符串形式存储数据的。如果我们想要通过json传送文件或者图片的话,必然涉及到要将图片或文件读取为字节并转为json放入字符串中,但是这其中存在一个问题java的字符都是由Unicode编码的,可以转换为2个字节的数据,这两个字节的值可能不在ASCII码中。而大多计算机都是用ASCII存储数据,比如在网络传输中如果遇到只能处理ascii字符的那么不能显示的字符将被错误处理。
 所以我们需要将要传输的图片字符串进行一定的处理,这种处理就是将不能显示的字符加密成能显示的字符,比如像BASE64加密,将传输的字符串加密成64个可显示字符。64个字符最多需要6位。那么每6个bit插入0xxxxxx0字节中,这样加密后原来的8n个bit现在要加密成8n/6个字节了,整体会增大1/3大小。这种方式虽说加密,但是可以轻松解密的。如果面对非二进制文件还可以用java的GZIP进行压缩然后加密。

2、上代码,不解释了

测试服务端

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * @author Lenvov
 *
 */
 @WebServlet(name="downloadservlet", urlPatterns={"/download"})
public class DownLoadServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = req.getServletContext().getResourceAsStream("img/leetcode.png");

        //InputStream is = new FileInputStream("img/leetcode.png");
        BufferedInputStream bis = new BufferedInputStream(is,1024);
        int len = 0;
        byte[] buf = new byte[1024];

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = bis.read(buf))!=-1){
            bos.write(buf, 0, len);
        }
        bis.close();
        is.close();

        //将图片写入json中
        String data = Base64.encode(bos.toByteArray());
        String json = "{'img': '"+data+"'}";
        System.out.println(json);
        resp.getOutputStream().write(json.getBytes());

    }
}

测试客户端

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


/**
 * @author Lenvov
 *
 */
public class DownClient {


    public static void main(String[] args) {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            url = new URL("http://localhost/WebTest/download");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(false);
            conn.connect();
            is = conn.getInputStream();

            int len = 0;
            byte[] buf = new byte[1024];

            while((len = is.read(buf))!=-1){
                bos.write(buf, 0, len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn.disconnect();
        }
        String jsonstr = new String(bos.toByteArray());
        System.out.println("----"+jsonstr);
        File f = new File("test.png");
        JsonObject jsono = new JsonParser().parse(jsonstr).getAsJsonObject();

        String imgdata = jsono.get("img").getAsString();

        byte[] bdata = Base64.decode(imgdata);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);

            fos.write(bdata);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值