Flutter Http请求库 dio 代码封装

Flutter Http请求库 dio 代码封装

**

新增HttpUtils.dart

**

import 'package:dio/dio.dart';
import 'dart:async';

//**********************************************************************************
//
// 文件名称:HttpUtils.dart
//
/ 
//
// 创建日期:2020-01-07
//
// 文件描述:Dio 封装 restful 请求 GET、POST、DELETE、PATCH
// * 主要作用为统一处理相关事务:
//*  - 统一处理请求前缀;
//*  - 统一打印请求信息;
//*  - 统一打印响应信息;
//*  - 统一打印报错信息;
// 修改履历:
// ---------------------------------------------------------------------------------
// 修改日期     修改者  修改标识   修改描述 (首行为示例)
// 2020/1/7    李军凯             链接Api验证登陆账号密码
//
//**********************************************************************************
class HttpUtils {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'http://10.0.2.2/api';//10.0.2.2//127.0.0.1
  //请求时间
  static const int CONNECT_TIMEOUT = 10000;
  //响应时间
  static const int RECEIVE_TIMEOUT = 10000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  /// request method
  static Future<Map> request(String url,
      {data, method, contentTypeString}) async {
    data = data ?? {};
    method = method ?? 'GET';
    contentTypeString = contentTypeString ?? 'application/json;charset=UTF-8';

    /// 打印请求相关信息:请求地址、请求方式、请求参数
    print('请求地址:【' + method + '  ' + url + '】');
    print('请求参数:' + data.toString());
    
    clear();
    Dio dio = createInstance();

    var result; 

    try {

      Response response = await dio.request(url,
          data: data,
          options: new Options(method: method, contentType: contentTypeString));

      result = response.data;

      /// 打印响应相关信息
      print('响应数据:' + response.toString());
    } on DioError catch (e) {

      ErrorEntity en = new ErrorEntity().createErrorEntity(e); 
      /// 打印请求失败相关信息
      print('请求出错:' + en.message);

    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性:请求前缀、连接超时时间、响应超时时间
      BaseOptions options = new BaseOptions(
        baseUrl: API_PREFIX,
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT, 
      );

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }
}

//请求错误类
class ErrorEntity {
  int code;
  String message;

  ErrorEntity({this.code, this.message});

  // 错误信息
  ErrorEntity createErrorEntity(DioError error) {
    switch (error.type) {
      case DioErrorType.CANCEL:
        {
          return ErrorEntity(code: -1, message: "请求取消");
        }
        break;
      case DioErrorType.CONNECT_TIMEOUT:
        {
          return ErrorEntity(code: -1, message: "连接超时");
        }
        break;
      case DioErrorType.SEND_TIMEOUT:
        {
          return ErrorEntity(code: -1, message: "请求超时");
        }
        break;
      case DioErrorType.RECEIVE_TIMEOUT:
        {
          return ErrorEntity(code: -1, message: "响应超时");
        }
        break;
      case DioErrorType.RESPONSE:
        {
          try {
            int errCode = error.response.statusCode;
            String errMsg = error.response.statusMessage;
            // return ErrorEntity(code: errCode, message: errMsg);
            switch (errCode) {
              case 400:
                {
                  return ErrorEntity(code: errCode, message: "请求语法错误");
                }
                break;
              case 403:
                {
                  return ErrorEntity(code: errCode, message: "服务器拒绝执行");
                }
                break;
              case 404:
                {
                  return ErrorEntity(code: errCode, message: "无法连接服务器");
                }
                break;
              case 405:
                {
                  return ErrorEntity(code: errCode, message: "请求方法被禁止");
                }
                break;
              case 500:
                {
                  return ErrorEntity(code: errCode, message: "服务器内部错误");
                }
                break;
              case 502:
                {
                  return ErrorEntity(code: errCode, message: "无效的请求");
                }
                break;
              case 503:
                {
                  return ErrorEntity(code: errCode, message: "服务器挂了");
                }
                break;
              case 505:
                {
                  return ErrorEntity(code: errCode, message: "不支持HTTP协议请求");
                }
                break;
              default:
                {
                  return ErrorEntity(code: errCode, message: "未知错误");
                }
            }
          } on Exception catch (_) {
            return ErrorEntity(code: -1, message: "未知错误");
          }
        }
        break;
      default:
        {
          return ErrorEntity(code: -1, message: error.message);
        }
    }
  }
}

如何使用?

 var result = await HttpUtils.request(
                                '/MoveApp/AppLogin',
                                method: HttpUtils.POST,
                                data: {'name': _name, 'password': _pwd});
发布了8 篇原创文章 · 获赞 0 · 访问量 88
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览