http通信,Android Gzip压缩解压

  1. import java.io.ByteArrayInputStream;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.util.zip.GZIPInputStream;
  5. import java.util.zip.GZIPOutputStream;
  6. /**
  7. *
  8. * 开发公司:sojson.com<br/>
  9. * 版权:sojson.com<br/>
  10. * <p>
  11. *
  12. * 字符串压缩
  13. *
  14. * <p>
  15. *
  16. * 区分 责任人 日期    说明<br/>
  17. * 创建 周柏成 2015年12月19日  <br/>
  18. * <p>
  19. * *******
  20. * <p>
  21. * @author zhou-baicheng
  22. * @email json@sojson.com
  23. * @version 1.0,2015年12月19日 <br/>
  24. *
  25. */
  26. public class GZIP {
  27. /**
  28. * 字符串的压缩
  29. *
  30. * @param str
  31. * 待压缩的字符串
  32. * @return 返回压缩后的字符串
  33. * @throws IOException
  34. */
  35. public static String compress(String str) throws IOException {
  36. if (null == str || str.length() <= 0) {
  37. return str;
  38. }
  39. // 创建一个新的 byte 数组输出流
  40. ByteArrayOutputStream out = new ByteArrayOutputStream();
  41. // 使用默认缓冲区大小创建新的输出流
  42. GZIPOutputStream gzip = new GZIPOutputStream(out);
  43. // 将 b.length 个字节写入此输出流
  44. gzip.write(str.getBytes());
  45. gzip.close();
  46. // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
  47. return out.toString("UTF-8");
  48. }
  49. /**
  50. * 字符串的解压
  51. *
  52. * @param str
  53. * 对字符串解压
  54. * @return 返回解压缩后的字符串
  55. * @throws IOException
  56. */
  57. public static String unCompress(String str) throws IOException {
  58. if (null == str || str.length() <= 0) {
  59. return str;
  60. }
  61. // 创建一个新的 byte 数组输出流
  62. ByteArrayOutputStream out = new ByteArrayOutputStream();
  63. // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
  64. ByteArrayInputStream in = new ByteArrayInputStream(str
  65. .getBytes("UTF-8"));
  66. // 使用默认缓冲区大小创建新的输入流
  67. GZIPInputStream gzip = new GZIPInputStream(in);
  68. byte[] buffer = new byte[256];
  69. int n = 0;
  70. while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
  71. // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
  72. out.write(buffer, 0, n);
  73. }
  74. // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
  75. return out.toString("UTF-8");
  76. }
  77. }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值