1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import 'package:dio/dio.dart';
- class DioHttpClient {
- static const int _DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
- static const int _DEFAULT_SEND_TIMEOUT = 60 * 1000;
- static const int _DEFAULT_RECEIVE_TIMEOUT = 60 * 1000;
- final Map<String, Dio> _mClientMap = <String, Dio>{};
- DioHttpClient._internal();
- static final DioHttpClient _instance = DioHttpClient._internal();
- factory DioHttpClient.getInstance() => _instance;
- Dio getClient(String baseUrl,
- {BaseOptions newOptions, List<Interceptor> interceptors}) {
- if (baseUrl == null || baseUrl.isEmpty) {
- throw Exception('baseUrl not be allowed null');
- }
- Dio client = _mClientMap[baseUrl];
- if (client != null) {
- if (interceptors != null) {
- client.interceptors.addAll(interceptors);
- }
- return client;
- }
- client = _createDioClient(baseUrl, options: newOptions);
- if (interceptors != null) {
- client.interceptors.addAll(interceptors);
- }
- _mClientMap[baseUrl] = client;
- return client;
- }
- Dio _createDioClient(String baseUrl, {BaseOptions options}) {
- if (options == null) {
- options = createOptions(baseUrl);
- }
- return Dio(options);
- }
- static BaseOptions createOptions(String baseUrl,
- {Map<String, dynamic> headers, Map<String, dynamic> queryParameters}) {
- return BaseOptions(
- connectTimeout: Duration(milliseconds: _DEFAULT_CONNECT_TIMEOUT),
- sendTimeout: Duration(milliseconds: _DEFAULT_SEND_TIMEOUT),
- receiveTimeout: Duration(milliseconds: _DEFAULT_RECEIVE_TIMEOUT),
- baseUrl: baseUrl,
- responseType: ResponseType.json,
- validateStatus: (status) {
- return true;
- },
- headers: headers,
- queryParameters: queryParameters,
- );
- }
- void release() {
- _mClientMap.clear();
- }
- }
|