请求接口返回数据的Content-type为br解析

Brotli是一种全新的数据格式,可以提供比Zopfli高20-26%的压缩比。

Brotli最初发布于2015年,用于网络字体的离线压缩。Google软件工程师在2015年9月发布了包含通用无损数据压缩的Brotli增强版本,特别侧重于HTTP压缩。

使用Brotli进行流压缩的内容编码类型已被提议使用“br”。

使用httpClient进行请求

需要引入的的依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.18</version>
</dependency>

<dependency>
    <groupId>org.brotli</groupId>
    <artifactId>dec</artifactId>
    <version>0.1.2</version>
</dependency>

解析:通过解析返回数据发现Content-Type为br,如果直接将返回流转化为字符串,则为乱码,需要用 BrotliCompressorInputStream 进行接收,然后再转为 InputStream 进而解析为字符串

 1 private static String deCodeStream(InputStream stream, String codeType) {
 2     if (codeType.contains("br")) {
 3         try {
 4             BrotliCompressorInputStream brStream = new BrotliCompressorInputStream(stream);
 5             BufferedInputStream inputStream = new BufferedInputStream(brStream);
 6             ByteArrayOutputStream result = new ByteArrayOutputStream();
 7             byte[] buffer = new byte[1024];
 8             int length;
 9             while ((length = inputStream.read(buffer)) != -1) {
10                 result.write(buffer, 0, length);
11             }
12             String str = result.toString(StandardCharsets.UTF_8.name());
13             System.out.println(str);
14             brStream.close();
15             inputStream.close();
16             result.close();
17             return str;
18         } catch (IOException e) {
19             System.out.println(e.getMessage());
20         }
21     }
22     return "";
23 }

猜你喜欢

转载自www.cnblogs.com/oumae/p/12681760.html
今日推荐