安卓开发 解析GZIP压缩发送过来byte[]

安卓开发中,经常会用到获取服务器端发送的数据,有些数据使用GZIP的格式压缩后发送过来的,下面就讲讲接收和解压缩

private void outJsonString(HttpServletResponse response, String json) {

response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.addHeader("charset", "charset=utf-8");
response.setHeader("Content-Encoding", "gzip");
ServletOutputStream sos;
GZIPOutputStream out = null;
try {
sos = response.getOutputStream();
out = new GZIPOutputStream(sos);
out.write(json.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("Close Stream Exception", e);
}
}
}
}

这个方法是将json字符数组用GZIPOutputStream 发送到客户端的,是getBytes("UTF-8")格式。

response.setHeader("Content-Encoding", "gzip");这个是头,发送的时候标明格式,接收的时候可以用来判断是什么格式

 public static String uncompress(ByteArrayInputStream in,String charset) {
        try {
           GZIPInputStream gInputStream = new GZIPInputStream(in);
           byte[] by = new byte[1024];
           StringBuffer strBuffer = new StringBuffer();
           int len = 0;
           while ((len = gInputStream.read(by)) != -1) {
            strBuffer.append( new String(by, 0, len,charset) );
           }
           return strBuffer.toString();
        } catch (IOException e) {
           e.printStackTrace();
        }
        return null;
        }

这个是解析的普通的方法,传的是inputStream流,和字符编码格式(utf-8),

例:

ByteArrayInputStream bais = new ByteArrayInputStream(content);
  sss =  GZIPUtil.uncompress(bais, "utf-8");

sss就是一个json字符串.。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值