You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用Retrofit获取原始HTTP响应的相关问题咨询

问题原因

该类型错误是因为Retrofit默认会通过内置转换器将响应体自动解析为String类型,不会保留原始ResponseBody或字节流,直接声明返回值为ResponseBody类型时就会触发强转失败。

实现方案
  • 首先在你的接口方法上添加@DioResponseType注解,指定响应类型为字节类型,跳过默认的字符串转换逻辑,将返回值声明为Response<List<int>>类型:
    import 'package:dio/dio.dart';
    import 'package:retrofit/retrofit.dart';
    
    part 'api_service.g.dart';
    
    @RestApi(baseUrl: "你的接口域名")
    abstract class ApiService {
      factory ApiService(Dio dio, {String baseUrl}) = _ApiService;
    
      @GET("/tar/file/download/path")
      @DioResponseType(ResponseType.bytes)
      Future<Response<List<int>>> getTarFile(@Query("fileId") String fileId);
    }
    
  • 调用接口后直接从响应中提取原始字节数据,传入TarReader解析即可:
    import 'package:tar/tar.dart';
    
    // 调用接口
    final response = await apiService.getTarFile("目标文件ID");
    // 直接获取原始字节数组
    final List<int> tarBytes = response.data!;
    // 传入TarReader解析
    final reader = TarReader(Stream.value(tarBytes));
    while (await reader.moveNext()) {
      final entry = reader.current;
      // 处理tar内的各个文件条目
    }
    await reader.cancel();
    
  • 如果需要用ResponseBody类型接收,可将响应类型指定为stream,返回值声明为ResponseBody:
    @GET("/tar/file/download/path")
    @DioResponseType(ResponseType.stream)
    Future<ResponseBody> getTarFile(@Query("fileId") String fileId);
    
    调用时直接取ResponseBody的stream属性即可:
    final responseBody = await apiService.getTarFile("目标文件ID");
    final reader = TarReader(responseBody.stream);
    
注意事项
  • 该接口不要配置任何自定义的JSON/字符串转换器,否则仍会触发自动类型转换导致报错
  • 方法上的@DioResponseType注解优先级高于Dio实例的全局响应类型配置,无需修改全局配置

内容的提问来源于stack exchange,提问作者sina .s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:45:03