https://www.jianshu.com/p/5ead0cf96642
Several benefits package network requests:
1, to facilitate unified configuration request parameters, such as header, public parameter, encrypted rules
2, to facilitate debugging, print log
3, the code to optimize performance, to avoid abuse everywhere new object construct single global Example
4, simplify requesting step, exposing only the response data required in response to the error correction unified
5, the base class encapsulates the data interface, simplified analytical process
results example:
HttpManager definition
The overall configuration of a single embodiment, parameter configuration request, the generic configuration GET \ POST, support handover 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 DioError catch