Flutter 网络请求之基于dio的简单封装

dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等。本文是基于dio库的简单二次封装,以适应我们平常开发中常用的get请求和post请求。

添加依赖

 

dependencies:
  dio: ^2.1.0

dio封装

首先,对dio进行初始化。这里使用工厂构造函数创建DioUtil,在Dart中,当实现一个使用 factory 关键词修饰的构造函数时,这个构造函数不必创建类的新实例。

 

  static final DioUtil _instance = DioUtil._init();
  static Dio _dio;

  factory DioUtil() {
    return _instance;
  }

  DioUtil._init() {
    _dio = new Dio();
  }

设置BaseOptions参数,可以设置网络请求超时时间,设置baseUrl。dio默认请求contentType为application/json,如果需要设置为application/x-www-form-urlencoded,需在BaseOptions中单独设置。在BaseOptions.hearders中可以添加自定义的网络请求头信息。

 

  static BaseOptions getDefOptions() {
    BaseOptions options = BaseOptions();
    options.connectTimeout = 10 * 1000;
    options.receiveTimeout = 20 * 1000;
    options.baseUrl = ‘ http://www.mocky.io/)’
    options.contentType = ContentType.parse('application/x-www-form-urlencoded');

    Map headers = Map();
    headers['Accept'] = 'application/json';

    String platform;
    if(Platform.isAndroid) {
      platform = "Android";
    } else if(Platform.isIOS) {
      platform = "IOS";
    }
    headers['OS'] = platform;
    options.headers = headers;

    return options;
  }

  setOptions(BaseOptions options) {
    _options = options;
    _dio.options = _options;
  }

网络请求过程

  • path 请求path路径,这里我们进行了restful请求处理,path路径参数放在pathParams中。
  • method 请求方式,可以为GET、POST、PUT、HEAD、DELETE、PATCH等,这字我们仅展示GET请求和POST请求。
  • pathParams path路径参数,Map数据结构
  • errorCallback 自定义错误处理,代码中_handleHttpError()方法进行统一的http错误码处理,如接口需单独处理某种错误码,可添加此回调方法。

返回数据如果为Map数据直接返回,如果为Json数据需通过json.decode解析之后再返回。

 

  Future> request(String path,{String method, Map pathParams, data, Function errorCallback}) async {
    ///restful请求处理
    if(pathParams != null) {
      pathParams.forEach((key, value) {
        if(path.indexOf(key) != -1) {
          path = path.replaceAll(":$key", value.toString());
        }
      });
    }

    Response response = await _dio.request(path, data: data, options: Options(method: method));

    if(response.statusCode == HttpStatus.ok || response.statusCode == HttpStatus.created) {
      try {
        if(response.data is Map) {
          return response.data;
        } else {
          return json.decode(response.data.toString());
        }
      } catch(e) {

        return null;
      }
    } else {
      _handleHttpError(response.statusCode);
      if(errorCallback != null) {
        errorCallback(response.statusCode);
      }
      return null;
    }
  }

GET请求

 

  Future> get(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.get, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

POST请求

 

  Future> post(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.post, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

完整代码

 

import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';

class Method {
  static final String get = "GET";
  static final String post = "POST";
  static final String put = "PUT";
  static final String head = "HEAD";
  static final String delete = "DELETE";
  static final String patch = "PATCH";
}

class DioUtil {
  static final DioUtil _instance = DioUtil._init();
  static Dio _dio;
  static BaseOptions _options = getDefOptions();

  factory DioUtil() {
    return _instance;
  }

  DioUtil._init() {
    _dio = new Dio();
  }

  static BaseOptions getDefOptions() {
    BaseOptions options = BaseOptions();
    options.connectTimeout = 10 * 1000;
    options.receiveTimeout = 20 * 1000;
    options.contentType = ContentType.parse('application/x-www-form-urlencoded');

    Map headers = Map();
    headers['Accept'] = 'application/json';

    String platform;
    if(Platform.isAndroid) {
      platform = "Android";
    } else if(Platform.isIOS) {
      platform = "IOS";
    }
    headers['OS'] = platform;
    options.headers = headers;

    return options;
  }

  setOptions(BaseOptions options) {
    _options = options;
    _dio.options = _options;
  }

  Future> get(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.get, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

  Future> post(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.post, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

  Future> request(String path,{String method, Map pathParams, data, Function errorCallback}) async {
    ///restful请求处理
    if(pathParams != null) {
      pathParams.forEach((key, value) {
        if(path.indexOf(key) != -1) {
          path = path.replaceAll(":$key", value.toString());
        }
      });
    }

    Response response = await _dio.request(path, data: data, options: Options(method: method));

    if(response.statusCode == HttpStatus.ok || response.statusCode == HttpStatus.created) {
      try {
        if(response.data is Map) {
          return response.data;
        } else {
          return json.decode(response.data.toString());
        }
      } catch(e) {

        return null;
      }
    } else {
      _handleHttpError(response.statusCode);
      if(errorCallback != null) {
        errorCallback(response.statusCode);
      }
      return null;
    }
  }

  ///处理Http错误码
  void _handleHttpError(int errorCode) {

  }

}

示例

 

  DioUtil().get('v2/5ca06a7d3300007200a87e01/:id', 
    pathParams: {
      ':id': 12
    },
    data: {
      'name':'tony',
      'age': 23
    },
    errorCallback: (statusCode) {
      print('Http error code : $statusCode');
    }
  ).then((data) {
    print('Http response: $data');
  });

 

你可能感兴趣的:(Flutter)