gpt4 book ai didi

java - 如何读取 brotli 压缩字符串?

转载 作者:行者123 更新时间:2023-12-02 00:10:37 24 4
gpt4 key购买 nike

我从网站获取 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/非 brotli(gzip 压缩等)流。

关于java - 如何读取 brotli 压缩字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com