PHP gzcompress 压缩,java实现gzuncompress

3/8/2017来源:ASP.NET技巧人气:699

1、php服务压缩数据 将字符串urlencode(因为压缩之后的字符串会有非显示字符):

x%DAKLJNIMK%CF%C8%CC%CA%CE%01%00%1E%B8%04%CF $str = "abcdefghijkl"; $str = urlencode(gzcomPRess($str, 9));//为了字符串字符可见

2、java解压 由于PHP gzcompress使用ZLIB压缩,因此java选择对应的压缩算法解压。 有一点是特别要注意的,一定要设置字符集,由于系统一般是UTF-8编码。

public static void main(String[] args) throws IOException { String tmp = "x%DAKLJNIMK%CF%C8%CC%CA%CE%01%00%1E%B8%04%CF"; String decodeTmp = URLDecoder.decode(tmp,"ISO-8859-1"); System.out.println(decompress(decodeTmp)); } public static String decompress(String data) throws UnsupportedEncodingException { return decompress(data,"ISO-8859-1"); } public static String decompress(String data, String charset) throws UnsupportedEncodingException { byte[] bytes = data.getBytes(charset); byte[] output = new byte[0]; Inflater decompresser = new Inflater(); decompresser.reset(); decompresser.setInput(bytes); ByteArrayOutputStream o = new ByteArrayOutputStream(bytes.length); try { byte[] buf = new byte[1024]; while (!decompresser.finished()) { int i = decompresser.inflate(buf); o.write(buf, 0, i); } output = o.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { o.close(); } catch (IOException e) { e.printStackTrace(); } } decompresser.end(); return new String(output); }