安卓开发中,经常会用到获取服务器端发送的数据,有些数据使用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字符串.。