最近有个需求要求对长字符串进行gzip压缩,然后在js进行解压缩的操作:
public static void main(String[] args) {
try {
String longString = "www.baidu.com";
// GZIP压缩后的数据
byte[] compress = compress(longString.getBytes());
//通过Base64转成字符串
String longStringEncoded = Base64.getEncoder().encodeToString(compress);
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] compress(byte[] data) throws IOException {
if (data == null || data.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(data);
gzip.close();
return out.toByteArray();
}
public static byte[] uncompress(byte[] data) throws IOException {
if (data == null || data.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
GZIPInputStream gzip = new GZIPInputStream(inputStream);
byte[] buffer = new byte[256];
int n;
while ((n = gzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
gzip.close();
inputStream.close();
return out.toByteArray();
}
//后端压缩后的字符串 let encodeDpUrl = 'H4sIAAAAAAAAACsvL9dLSsxMKdVLzs8FAA3FGxcNAAAA'; //Base64解码 let gzipUrl = atob(encodeDpUrl); // 将二进制字符串转换为字符数字数组 let charData = gzipUrl.split('').map(function (x) { return x.charCodeAt(0); }); //将数字数组转换为字节数组 let binData = new Uint8Array(charData); //unzip 需要引入 pako.js文件 https://github.com/nodeca/pako var data = pako.inflate(binData); // 将字节数组转字符串 let longString = String.fromCharCode.apply(null, new Uint16Array(data)); console.info(longString);
记:url编码解码问题 //后端进行url编码, String encodeUrl = URLEncoder.encode(要编码的URL, Constant.ENCODING_UTF_8); // 前端进行url解码 let decodeURI = decodeURIComponent(要解码的URL);
标签:解压,js,let,gzip,new,byte,data,out From: https://www.cnblogs.com/zsw-wkx/p/17012712.html