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

服务器端:
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();
}

猜你喜欢

转载自sdkongkong.iteye.com/blog/1987517
今日推荐