Flutter Dio 网络框架的二次封装

dio 二次封装

功能点

1、支持get、post、put、delete 四种请求方式

2、支持文件上传并获取上传进度

3、支持最大重试请求次数

4、支持通过传递 解析方法,对数据进行解析,出现异常并捕获异常

所使用到的插件如下:

  # HTTP 请求
  dio: ^5.4.0
  cookie_jar: ^4.0.8
  dio_cookie_manager: ^3.1.1

创建dio请求类 net_work_http_task.dart

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter/foundation.dart';

// 请求类型
enum HttpMethod {
  get,
  post,
  put,
  delete,
}

// HTTP 请求base类
class NetWorkHttpTask {
  // 重写构造方法
  NetWorkHttpTask({
    required this.path,
    this.httpMethod = HttpMethod.post,
    this.timeOut = 30000,
    this.timeOutMax = 0,
  });

  // 请求类型
  HttpMethod httpMethod;

  // 最大超时请求次数
  int timeOutMax;

  // 超时时间
  int timeOut;

  // ip
  String ip = "Https://192.168.1.1";

  // 端口号
  int port = 8080;

  // 请求链接
  String path;

  // 请求参数
  Map queryParameters = {};

  // 配置共同参数
  void configParam() {}

  // 请求返回内容
  Response? response;

  // 请求异常
  Exception? exception;

  /// 请求基础配置
  late var baseOptions = BaseOptions(
      baseUrl: "$ip:$port",
      connectTimeout: Duration(seconds: timeOut),
      receiveTimeout: Duration(seconds: timeOut),
      responseType: ResponseType.json,
      contentType: "multipart/form-data; boundary=",
      headers: {"X-Access-Token": ""});

  /// 全局共同Dio
  var shareDio = (BaseOptions baseOptions) {
    Dio dio = Dio(baseOptions);
    var cookieJar = CookieJar();
    dio.interceptors.add(CookieManager(cookieJar));
    //简单粗暴方式处理校验证书方法
    (dio.httpClientAdapter as IOHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) {
        return true;
      };
      return null;
    };
    return dio;
  };

  // 获取文件上传进度
  Function(int progress, int total)? fileUploadProgress;

  /// 文件上传
  Future fileUploadRequest(FormData formData) async {
    Dio dio = shareDio(baseOptions);
    try {
      response = await dio.post(path, data: formData,
          onSendProgress: (int progress, int total) {
        if (fileUploadProgress != null) {
          fileUploadProgress!(progress, total);
        }
      });
      if (response == null || response?.data == null) {
        return null;
      } else {
        return response?.data;
      }
    } catch (exception) {
      this.exception = exception as Exception?;
      _requestExceptionHandling();
      return null;
    }
  }

  /// 开始请求
  Future httpRequest() async {
    Dio dio = shareDio(baseOptions);
    try {
      response = _requestRetry(dio) as Response?;
      if (response == null || response?.data == null) {
        return null;
      } else {
        return response?.data;
      }
    } catch (exception) {
      this.exception = exception as Exception?;
      _requestExceptionHandling();
      return null;
    }
  }

  /// 设置最大请求及请求次数
  Future _requestRetry(Dio dio) async {
    for (int i = 0; i <= timeOutMax; i++) {
      try {
        return await _dioRequest(dio);
      } on DioException catch (error) {
        if (error.type == DioExceptionType.connectionTimeout ||
            error.type == DioExceptionType.sendTimeout ||
            error.type == DioExceptionType.receiveTimeout) {
          if (i <= timeOutMax) {
            continue;
          }
        }
        rethrow;
      }
    }
    return null;
  }

  /// 请求类型
  Future _dioRequest(Dio dio) async {
    Response? response;
    switch (httpMethod) {
      case HttpMethod.post:
        if (queryParameters.isEmpty) {
          response = await dio.post(path);
        } else {
          response = await dio.post(path, queryParameters: queryParameters);
        }
        break;
      case HttpMethod.get:
        if (queryParameters.isEmpty) {
          response = await dio.get(path);
        } else {
          response = await dio.get(path, queryParameters: queryParameters);
        }
        break;
      case HttpMethod.put:
      case HttpMethod.delete:
        assert(false, "put delete暂不支持");
        break;
    }
    return response;
  }

  /// 获取请求成功状态
  bool requestStatus() {
    return response != null && response?.statusCode == 200;
  }

  /// 请求异常处理
  void _requestExceptionHandling() {
    if (kDebugMode) {
      print(exception.toString());
    }
  }

  /// 解析数据
  Future parseData(T? Function(Map json) function) async {
    final normalResult = await httpRequest();
    try {
      return normalResult == null ? null : function(normalResult);
    } catch (e) {
      if (kDebugMode) {
        print(e.toString());
      }
      return null;
    }
  }
}

到此完成了dio的网络框架的二次封装。

下面写一个测试例子

创建一个Model类 home_model.dart


// To parse this JSON data, do
//
//     final homeModel = homeModelFromJson(jsonString);

import 'dart:convert';

HomeModel homeModelFromJson(String str) => HomeModel.fromJson(json.decode(str));

String homeModelToJson(HomeModel data) => json.encode(data.toJson());

class HomeModel {
  String? greeting;
  List? instructions;

  HomeModel({
    this.greeting,
    this.instructions,
  });

  factory HomeModel.fromJson(Map json) => HomeModel(
    greeting: json["greeting"],
    instructions: json["instructions"] == null ? [] : List.from(json["instructions"]!.map((x) => x)),
  );

  Map toJson() => {
    "greeting": greeting,
    "instructions": instructions == null ? [] : List.from(instructions!.map((x) => x)),
  };
}

请求类和模型类创建完成后,下面就是使用了

    NetWorkHttpTask task = NetWorkHttpTask(path: "api/home");
    task.parseData(HomeModel.fromJson).then((value) {
      print(value);
    });

到此就完成了使用

你可能感兴趣的:(flutter,网络)