Flutter 网络层封装(dio封装)

2021-04-15  本文已影响0人  JamieChen

一、导入dio框架

二、基本设置

管理类Network

管理类会持有使用NetworkRequest做的每次请求, 下文中会介绍,此做法是为了对App内的所有请求做统一管理,通过这层设计可以方便的对单个或多个请求进行停止、监听等操作。
以下是一些详细的封装描述;
Host

header

content type

利用枚举值简要的设置了content type 好处是不用输入字符串,容错程度更高

enum NetworkContentType {
  multipartFormData,// 'multipart/form-data'
  applicationXwwwFormUrlencoded,// 'application/x-www-form-urlencoded; charset=utf-8'
  applicationJson,// 'application/json'
}

Parameter

创建NetworkParameter类,此层处理是为了对post请求的参数做统一处理,所以将参数分为通用参数generalParameters 一般参数parameters及完整参数completedParameters三层;

class NetworkParameter {

  //通用参数,指服务端接口需要传递的通用参数,如,sign | sessionKey secretKey 等;
  Map<String, dynamic> generalParameters = Map();

  Map<String, dynamic> parameters = Map();
  Map<String, dynamic> completedParameters = Map();

  // 子类可通过重写该方法处理post请求前的参数,如sign等
  Map processCompletedParameters() {
    completedParameters.addAll(generalParameters);
    completedParameters.addAll(parameters);

    return completedParameters;
  }
  

}

超时时间

connectTimeout
receiveTimeout

三、Request

将每个API接口单独设计为一个Request类,这样做的目的是便于API管理,在API参数或路径做变更时不用在项目中一个个的去改,
设置了一个Request基类,如下,App在使用过程中继承此基类

enum MethodType {
  post, // 'post'
  get, // 'get'
}

class NetworkRequest {
  MethodType methodType = MethodType.post;

  String path;

  Map<String, String> header;
  NetworkContentType contentType = NetworkContentType.applicationJson;

  NetworkParameter parameter;

  ResponceSuccess successBlock;
  ResponceError failureBlock;
  NetworkSessionTask sessionTask;
  bool requesting;
  Dio dio;
  // Map<String, dynamic> parameters = Map();

  Function processSuccess({Response response}) {
    requesting = false;
    if (successBlock != null) {
      successBlock(response);
    }
  }

  Function processFailure({Response errorResponse}) {
    requesting = false;
    if (failureBlock != null) {
      failureBlock(errorResponse);
    }
  }

  Function stop() {}

  Function start(ResponceSuccess successCallBack, ResponceError failCallBack) {
    requesting = true;
    this.successBlock = successCallBack;
    this.failureBlock = failCallBack;
    
    if (methodType == MethodType.post) {
      Network.instance.processObtainRequest(request: this);
    } else {}
  }
}

App自己设置一个继承于NetworkRequest的基类,此层继承的作用是设置parameter,在StudyParameter中对于post请求的公共参数及sign做统一处理;

class StudyRequest extends NetworkRequest {
  StudyRequest(){
    super.parameter = StudyParameter();
  }

  @override
  Function start(successCallBack, failCallBack) {
    // TODO: implement start
    return super.start(successCallBack, failCallBack);
  }
}

App继承基类后的样子


// 更新用户昵称接口
class MineInformationUpdateNicknameRequest extends StudyRequest {
  final String nickname;

  MineInformationUpdateNicknameRequest({this.nickname}) {
    path = StudyAPIClient.updateUserNickname;
    contentType = NetworkContentType.applicationJson;
    parameter.parameters = {"nickname": nickname};
  }
}

请求
Request中包含一个NetworkSessionTask类,将dio置于其中,类似于将每次的请求当作一个会话,
1.普通请求

(1).post

(2).get

2.上传

3.下载

四、Response

五、网络请求管理

取消请求

六、拦截器

代理模式实现拦截器到日志的分发,
networkInterceptorsDelegate

// 请求
typedef NetworkInterceptorsOnRequest = void Function(RequestOptions options, RequestInterceptorHandler handler);
/// 结果
typedef NetworkInterceptorsOnResponse = void Function(Response response, ResponseInterceptorHandler handler);
/// 错误
typedef NetworkInterceptorsOnError = void Function(DioError err, ErrorInterceptorHandler handler);

mixin NetworkInterceptorsDelegate {
  void workDone();
  NetworkInterceptorsOnRequest onRequestDone;
  NetworkInterceptorsOnResponse onResponseDone;
  NetworkInterceptorsOnError onErrorDone;
}

class NetworkInterceptors extends InterceptorsWrapper {
  NetworkInterceptorsDelegate delegate;

  NetworkInterceptorsOnRequest networkInterceptorsOnRequest;

  NetworkInterceptorsOnResponse networkInterceptorsOnResponse;

  NetworkInterceptorsOnError networkInterceptorsOnError;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // TODO: implement onRequest
    super.onRequest(options, handler);
    if (networkInterceptorsOnRequest != null) {
      networkInterceptorsOnRequest(options,handler);
    }
    if (delegate != null) {
      delegate.onRequestDone(options, handler);

    }
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // TODO: implement onResponse
    super.onResponse(response, handler);
    if (networkInterceptorsOnResponse != null) {
      networkInterceptorsOnResponse(response,handler);
    }

    if (delegate != null) {
      delegate.onResponseDone(response,handler);
    }
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    // TODO: implement onError
    super.onError(err, handler);
    if (networkInterceptorsOnError != null) {
      networkInterceptorsOnError(err,handler);
    }

    if (delegate != null) {
      delegate.onErrorDone(err,handler);
    }
  }




}

利用拦截器做网络请求日志

上一篇下一篇

猜你喜欢

热点阅读