Flutter中如何解压brotli压缩的HTTP响应内容
Flutter中解压Brotli(br)压缩响应的解决方案
方案1:使用dio客户端集成Brotli拦截器(推荐)
dio是Flutter生态中最常用的HTTP请求库,可通过扩展快速实现br压缩响应的自动解压:
- 首先添加依赖到
pubspec.yaml:
dependencies: dio: ^5.4.0 dio_brotli_transformer: ^1.0.0
- 初始化dio实例时配置Brotli转换器:
import 'package:dio/dio.dart'; import 'package:dio_brotli_transformer/dio_brotli_transformer.dart'; void main() { final dio = Dio(); // 配置后会自动识别br编码响应并解压,同时保留原生gzip解压能力 dio.transformer = DioBrotliTransformer(); }
配置完成后所有请求的br压缩响应都会自动解压,无需额外处理返回内容。
方案2:手动解压Brotli内容
如果使用原生http库或不想修改全局客户端配置,可直接对返回的二进制流手动解码:
- 首先添加依赖到
pubspec.yaml:
dependencies: brotli: ^0.6.0 http: ^1.1.0
- 发起请求后手动识别并解码响应:
import 'package:http/http.dart' as http; import 'package:brotli/brotli.dart'; import 'dart:convert'; Future<String> requestApi() async { final response = await http.get( Uri.parse('你的API接口地址'), // 请求头明确告知服务端支持br编码,避免部分服务端不返回压缩内容 headers: {'Accept-Encoding': 'br'}, ); if (response.headers['content-encoding'] == 'br') { // 必须基于二进制字节流解码,直接解析response.body会得到乱码 final decompressedBytes = brotliDecode(response.bodyBytes); return utf8.decode(decompressedBytes); } return response.body; }
注意事项
- 所有方案都默认兼容gzip、deflate等常规压缩格式,无需额外适配
- 处理br响应时禁止直接对
response.body做字符串解析,压缩内容为二进制格式,必须基于response.bodyBytes处理
内容的提问来源于stack exchange,提问作者Jestin
相关产品推荐
相关产品推荐

