https://www.jianshu.com/p/5ead0cf96642
封装网络请求的几个好处:
1、便于统一配置请求参数,如header,公共参数,加密规则等
2、方便调试,日志打印
3、优化代码性能,避免到处滥new对象,构建全局单例
4、简化请求步骤,只暴露需要的响应数据,而对错误的响应统一回调
5、对接口数据的基类封装,简化解析流程
效果示例:
HttpManager的定义
构造全局单例,配置请求参数,配置通用的GET\POST,支持baseUrl的切换
class HttpManager {
static HttpManager _instance = HttpManager._internal(); Dio _dio; factory HttpManager() => _instance; ///通用全局单例,第一次使用时初始化 HttpManager._internal({String baseUrl}) { if (null == _dio) { _dio = new Dio(new BaseOptions( baseUrl: Address.BASE_URL_RELEASE, connectTimeout: 15000)); _dio.interceptors.add(new LogsInterceptors()); _dio.interceptors.add(new ResponseInterceptors()); } } static HttpManager getInstance({String baseUrl}) { if (baseUrl == null) { return _instance._normal(); } else { return _instance._baseUrl(baseUrl); } } //用于指定特定域名,比如cdn和kline首次的http请求 HttpManager _baseUrl(String baseUrl) { if (_dio != null) { _dio.options.baseUrl = baseUrl; } return this; } //一般请求,默认域名 HttpManager _normal() { if (_dio != null) { if (_dio.options.baseUrl != Address.BASE_URL_RELEASE) { _dio.options.baseUrl = Address.BASE_URL_RELEASE; } } return this; } ///通用的GET请求 get(url, params, {noTip = false}) async { Response response; try { response = await _dio.get(url, queryParameters: params); } on DioError catch (e) { return resultError(e); } if (response.data is DioError) { return resultError(response.data['code']); } return response.data; } ///通用的POST请求 post(url, params, {noTip = false}) async { Response response; try { response = await _dio.post(url, data: params); } on