用pako.js压缩字符串,如何在后端用java解开?
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                在前端使用pako.js压缩字符串,然后在后端使用Java解压,你可以使用Java的Inflater类来解压经过pako.js压缩的数据。以下是一个简单的例子:
前端(JavaScript):
const pako = require('pako');
 
// 假设这是你通过pako压缩过的数据
const compressedData = pako.deflate('这是一个压缩的字符串', { to: 'string' });
 
// 将compressedData发送到服务器后端(Java):
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
 
public class Decompressor {
    public static String decompress(String compressedStr) {
        byte[] compressedBytes = Base64.getDecoder().decode(compressedStr);
        ByteArrayInputStream bis = new ByteArrayInputStream(compressedBytes);
        Inflater inflater = new Inflater();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedBytes.length);
 
        try {
            byte[] buffer = new byte[1024];
            int len;
            inflater.setInput(bis);
            while (!inflater.needsInput()) {
                len = inflater.inflate(buffer);
                if (len <= 0) {
                    break;
                }
                bos.write(buffer, 0, len);
            }
            bis.close();
            inflater.end();
 
            return new String(bos.toByteArray(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    public static void main(String[] args) {
        String compressedStr = "eJzT0yMAAGTvBe8="; // 这里应该是前端发送过来的压缩数据
        String decompressedStr = decompress(compressedStr);
        System.out.println(decompressedStr);
    }
}确保前端发送到服务器的数据是Base64编码的,并且在Java端使用相同的编码方式来解码。解压后的字符串应该是原始的压缩字符串。
评论已关闭