Flutter dio http 封装指南说明

warning: 这篇文章距离上次修改已过327天,其中的内容可能已经有所变动。



import 'package:dio/dio.dart';
 
class HttpUtils {
  static final BaseOptions baseOptions = BaseOptions(
    baseUrl: 'https://www.example.com',
    connectTimeout: 5000,
    receiveTimeout: 3000,
  );
 
  static final Dio dio = Dio(baseOptions);
 
  // 发起GET请求
  static Future<Response> get(String path, {Map<String, dynamic>? queryParameters, Options? options}) async {
    try {
      return await dio.get(path, queryParameters: queryParameters, options: options);
    } on DioError catch (e) {
      // 处理请求错误
      print('请求出错: ${e.message}');
      rethrow;
    }
  }
 
  // 发起POST请求
  static Future<Response> post(String path, {data, Options? options}) async {
    try {
      return await dio.post(path, data: data, options: options);
    } on DioError catch (e) {
      // 处理请求错误
      print('请求出错: ${e.message}');
      rethrow;
    }
  }
 
  // 添加请求拦截器
  static void addRequestInterceptor(RequestInterceptor handler) {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) async {
        // 在这里根据需要修改请求头或其他信息
        // 例如添加token
        // options.headers['Authorization'] = 'Bearer your-token';
        handler.next(options); // 继续请求
      },
    ));
  }
 
  // 添加响应拦截器
  static void addResponseInterceptor(ResponseInterceptor handler) {
    dio.interceptors.add(InterceptorsWrapper(
      onResponse: (Response response, ResponseInterceptorHandler handler) async {
        // 在这里处理响应数据,比如解析数据
        // 例如解析json
        // var jsonData = jsonDecode(response.data);
        // response.data = jsonData;
        handler.next(response); // 继续处理响应
      },
    ));
  }
}
 
// 使用示例
void main() async {
  // 发起GET请求
  var response = await HttpUtils.get('/some-endpoint');
  print(response.data);
 
  // 添加请求拦截器
  HttpUtils.addRequestInterceptor((RequestOptions options) {
    // 在这里添加拦截逻辑
  });
 
  // 添加响应拦截器
  HttpUtils.addResponseInterceptor((Response response) {
    // 在这里处理响应逻辑
  });
}

这个示例代码展示了如何封装一个简单的Dio HTTP请求工具类,包括GET和POST请求的基本使用,以及如何添加请求和响应拦截器。这是一个很好的学习资源,对于初学者来说可以学习到如何组织HTTP请求代码,同时也可以为开发者提供一个扩展和自定义的起点。

最后修改于:2024年08月08日 11:51

评论已关闭

推荐阅读

AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日
python之plot()和subplot()画图
2024年11月26日
理解 DALL·E 2、Stable Diffusion 和 Midjourney 工作原理
2024年12月01日