我从网站获取brotli压缩的json字符串。我想解压缩并阅读它。

当我从响应中使用输入流时,我可以使用正确读取它

new BufferedReader(new InputStreamReader(new BrotliInputStream(response.getEntity().getContent())));


而当我将响应保存在字符串中并阅读时

BufferedReader rd = new BufferedReader(new InputStreamReader(new BrotliInputStream(IOUtils.toInputStream(responseAsString, "UTF-8"))));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
    result.append(line);
}
System.out.println(result);


我得到以下异常:

Exception in thread "main" java.io.IOException: Brotli stream decoding failed
    at org.brotli.dec.BrotliInputStream.read(BrotliInputStream.java:167)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.brotli.test.BrotliStringTest.main(BrotliStringTest.java:113)
Caused by: org.brotli.dec.BrotliRuntimeException: Unused space
    at org.brotli.dec.Decode.readHuffmanCodeLengths(Decode.java:226)
    at org.brotli.dec.Decode.readHuffmanCode(Decode.java:296)
    at org.brotli.dec.HuffmanTreeGroup.decode(HuffmanTreeGroup.java:53)
    at org.brotli.dec.Decode.readMetablockHuffmanCodesAndContextMaps(Decode.java:528)
    at org.brotli.dec.Decode.decompress(Decode.java:621)
    at org.brotli.dec.BrotliInputStream.read(BrotliInputStream.java:161)
    ... 8 more


编辑1:

我尝试使用Jsoup,发现它仅支持Gzipped流,并且在其HttpConnection类中不支持BrotliInputStream。关于这个有什么建议吗?

最佳答案

我已经这样解决了:

import org.brotli.dec.BrotliInputStream;

if(response.getLastHeader("content-encoding").getValue().equals("br")) { // check if getting brotli compressed stream
    rd = new BufferedReader(new InputStreamReader(new BrotliInputStream(response.getEntity().getContent())));
}
else {
    rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
}


这适用于brotli / non-brotli(已压缩等)流。

07-25 23:39