美文网首页Flutter
Flutter-网络请求框架

Flutter-网络请求框架

作者: 节庆007 | 来源:发表于2019-10-08 10:20 被阅读0次

    我现在采用的网络框架是基于dio的。
    线上工具类:

    import 'package:dio/dio.dart';
    import 'package:http_parser/http_parser.dart';
    import 'package:yxk_app/constant/functions.dart';
    import 'package:yxk_app/net/request_api.dart';
    import 'package:yxk_app/utils/data_utils.dart';
    import 'package:yxk_app/utils/log_utils.dart';
    
    /// 网络请求
    class RequstUtil {
      // token值
      static String token;
    
      // 初始化
      static final Dio _dio = new Dio(new BaseOptions(
          method: RequestApi.methodGet,
          baseUrl: RequestApi.baseUrl,
          connectTimeout: RequestApi.connectTimeout,
          receiveTimeout: RequestApi.receiveTimeout,
          followRedirects: true));
    
      /// 请求
      ///
      /// 必填字段:
      /// method 请求方法,如 RequestApi.methodGet
      /// uri 请求地址
      /// isBody 表单格式为false、json格式为true
      ///
      /// 可选字段:
      /// key 服务端返回数据中需要取得字段,不设置的话默认是同级code的data值
      /// responceSuccess 返回成功数据回调
      /// responceError 返回失败数据回调
      static doRequest(String method, String uri, bool isBody,
          {Map<String, dynamic> body,
          String key,
          ResponceSuccess responceSuccess,
          ResponceError responceError}) async {
        _httpJson(method, uri, isBody, data: body).then((resp) {
          doResponse(resp,
              key: key,
              responceSuccess: responceSuccess,
              responceError: responceError);
        });
      }
    
      /// 文件上传  返回json数据为字符串
      static Future putFile(String uri, String filePath,
          {ResponceSuccess responceSuccess, ResponceError responceError}) {
        String name =
            filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    
        FormData formData = FormData.fromMap({
          "multipartFile": MultipartFile.fromFile(filePath,
              filename: name, contentType: MediaType.parse("multipart/form-data")),
        });
    
        var enToken = token == null ? "" : Uri.encodeFull(token);
        return _dio
            .put<Map<String, dynamic>>("$uri?token=$enToken", data: formData)
            .then((resp) {
          doResponse(resp,
              responceSuccess: responceSuccess, responceError: responceError);
        });
      }
    
      /// 请求数据
      static Future<Response<Map<String, dynamic>>> _httpJson(
          String method, String uri, bool isBody,
          {Map<String, dynamic> data}) {
        Log.d('请求地址:$uri\n请求参数:$data');
    
        Options op = Options(method: method, headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        });
    
        if (isBody) {
          return _dio.request<Map<String, dynamic>>(uri,
              data: data ?? Map<String, dynamic>(), options: op);
        } else {
          return _dio.request<Map<String, dynamic>>(uri,
              queryParameters: data ?? Map<String, dynamic>(), options: op);
        }
      }
    
      /// 返回数据统一处理
      static void doResponse(Response<Map<String, dynamic>> resp,
          {String key,
          ResponceSuccess responceSuccess,
          ResponceError responceError}) {
        LogicError error = LogicError("-1", "未知异常");
    
        // 打印日志
        Log.d('返回数据:$resp');
    
        // 回调监听
        if (null != resp.data && null != resp.data['code']) {
          if (resp.data["code"] == "0" || resp.data["code"] == "200") {
            // 成功
            if (null != responceSuccess)
              responceSuccess(
                  !StringUtils.isEmpty(key) ? resp.data["data"][key] : resp.data);
            return;
          } else {
            // 失败
            error = new LogicError(resp.data["code"], resp.data['msg']);
    
            /// token失效 重新登录  后端定义的code码
            if (resp.data["code"] == RequestApi.tokenIllegalCode) {
              // todo 退出登录界面
    
            }
          }
        }
        if (null != responceError) responceError(error);
      }
    }
    
    /// 异常类
    class LogicError {
      final String errorCode;
      final String msg;
    
      LogicError(this.errorCode, this.msg);
    }
    
    enum PostType { json, form, file }
    

    api相关类:

    /// 请求api
    class RequestApi {
      /// 方法
      static final String methodGet = "get";
      static final String methodPost = "post";
      static final String methodPut = "put";
      static final String methodDellete = "delete";
    
      /// 网络请求配置信息
      static final String baseUrl = "${基础域名}"; // 基础域名
      static final int connectTimeout = 10 * 1000; // 连接超时时间
      static final int receiveTimeout = 10 * 1000; // 接收超时时间
    
      /// 错误信息
      static final String tokenIllegalCode = "-99"; // token失效code码
    
      /// 接口
      static String login = "${你自己的接口}"; // 用户登录
    }
    
    

    整体比较简单,注释也很全了,错误异常是一个异常类,正常的返回可能存在bool、String、Object、Map、List等等类型,这些自己可以采用dynamic提取最终数据,然后直接转换就可以了,也比较简单。

    相关文章

      网友评论

        本文标题:Flutter-网络请求框架

        本文链接:https://www.haomeiwen.com/subject/bmavpctx.html