简体   繁体   中英

Java Deflater Equivalent in Javascript

I'm trying to consume a web service that requires message sent to be compressed. The current implementation is done in Java, however, I want to port it over to Javascript. The compression works as follows:

String params = "hello";

byte[] bytes = params.getBytes();

ByteArrayOutputStream bao = new ByteArrayOutputStream(bytes.length);    
byte[] buffer = new byte[1024];
byte[] out = null;
int len;

Deflater compress = new Deflater();
compress.setInput(bytes);
compress.finish();
while(!compress.finished()) {
     len = compress.deflate(buffer);
     bao.write(buffer, 0, len);
}
out = bao.toByteArray(); 

//Output: [120, -100, -53, 72, -51, -55, -55, 7, 0, 6, 44, 2, 21]

I've tried using various inflate/deflate libraries like Zlib / Pako without any success:

function stringToUint(string) {
    var charList = string.split(''),
    uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}  

var bytes = stringToUint('hello'); 
var compressed = pako.deflate(bytes); 

//Output: [120, 156, 203, 72, 205, 201, 201, 7, 0, 6, 44, 2, 21]

Comparing outputs:

Java Output: [120, -100, -53, 72, -51, -55, -55, 7, 0, 6, 44, 2, 21]
JS   Output: [120,  156, 203, 72, 205, 201, 201, 7, 0, 6, 44, 2, 21]

感谢大家的帮助,看来字节数据是相同的,我只需要将其转换为有符号数组即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM