I use a special servlet that decompresses and compresses requests and responses
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException{ InputStream zipedStreamRequest = req.getInputStream(); String unzipJsonStr = ZipUtil.uncompressWrite(zipedStreamRequest); System.out.println("<---- ZIP request <----"); System.out.println(unzipJsonStr); MainHandler handler = new MainHandler(); String responseJson = handler.handle(unzipJsonStr); System.out.println("----> ZIP response ---->"); System.out.println(responseJson); OutputStream responseOutputStream = res.getOutputStream(); if (responseJson!=null) { ZipUtil.compressWrite(responseJson, responseOutputStream); } }
here is my ziputil class
public class ZipUtil { private static final int NB_BYTE_BLOCK = 1024; private static void compressWrite(InputStream in, OutputStream out) throws IOException{ DeflaterOutputStream deflaterOutput = new DeflaterOutputStream(out); int nBytesRead = 1; byte[] cur = new byte[NB_BYTE_BLOCK]; while (nBytesRead>=0){ nBytesRead = in.read(cur); byte[] curResized; if (nBytesRead>0){ if (nBytesRead<NB_BYTE_BLOCK){ curResized = new byte[nBytesRead]; System.arraycopy(cur, 0, curResized, 0, nBytesRead); } else { curResized = cur; } deflaterOutput.write(curResized); } } deflaterOutput.close(); } public static void compressWrite(String in, OutputStream out){ InputStream streamToZip = null; try { streamToZip = new ByteArrayInputStream(in.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { ZipUtil.compressWrite(streamToZip, out); } catch (IOException e) { e.printStackTrace(); } } private static void uncompressWrite(InputStream in, OutputStream out) throws IOException{ InflaterInputStream inflaterInputStream = new InflaterInputStream(in); int nBytesRead = 1; byte[] cur = new byte[NB_BYTE_BLOCK]; while (nBytesRead>=0){ nBytesRead = inflaterInputStream.read(cur); byte[] curResized; if (nBytesRead>0){ if (0<=nBytesRead && nBytesRead<NB_BYTE_BLOCK){ curResized = new byte[nBytesRead]; System.arraycopy(cur, 0, curResized, 0, nBytesRead); } else { curResized = cur; } out.write(curResized); } } out.close(); } public static String uncompressWrite(InputStream in){ ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { uncompressWrite(in, bos); } catch (IOException e1) { e1.printStackTrace(); } try { byte[] byteArr = bos.toByteArray(); String out = new String(byteArr, "UTF-8"); return out; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
}
source share