首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

服务器端跟客户端交互时的压缩

2013-12-15 
服务器端和客户端交互时的压缩服务器端:private byte[] compress(byte[] data) throws Exception {ByteArr

服务器端和客户端交互时的压缩
服务器端:
private byte[] compress(byte[] data) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
GZIPOutputStream gos = new GZIPOutputStream(baos);
gos.write(data, 0, data.length);
gos.finish();
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
return output;
}
private byte[] compress(byte[] data) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
GZIPOutputStream gos = new GZIPOutputStream(baos);
gos.write(data, 0, data.length);
gos.finish();
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
return output;
}

String json = caseReportService.findAppCaseQueryByPage(contentresult);
//System.out.println("json.length"+json.length());
byte[] output = compress(json.getBytes("UTF-8"));
//System.out.println("output.length"+output.length);
OutputStream out = response().getOutputStream();
response().setCharacterEncoding("UTF-8");
response().setHeader("Content-Encoding", "gzip"); 
response().setContentLength(output.length); 
//System.out.println(new String(output,"UTF-8"));
out.write(output);
out.flush();
out.close();

客户端 :
if (headerField != null && headerField.indexOf("gzip") > -1) {
result = zipToString(in);
} else {
result = inputStreamToString(in);
}
public static String zipToString(InputStream is) throws IOException {
GZIPInputStream gzin = new GZIPInputStream(is);

InputStreamReader isr = new InputStreamReader(gzin, "UTF-8");
java.io.BufferedReader br = new java.io.BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String tempbf;
while ((tempbf = br.readLine()) != null) {
sb.append(tempbf);
}
isr.close();
gzin.close();
System.out.println("sb to String: zip" + sb.toString());
return sb.toString();
}

热点排行