dio_client.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'package:dio/dio.dart';
  2. class DioHttpClient {
  3. static const int _DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
  4. static const int _DEFAULT_SEND_TIMEOUT = 60 * 1000;
  5. static const int _DEFAULT_RECEIVE_TIMEOUT = 60 * 1000;
  6. final Map<String, Dio> _mClientMap = <String, Dio>{};
  7. DioHttpClient._internal();
  8. static final DioHttpClient _instance = DioHttpClient._internal();
  9. factory DioHttpClient.getInstance() => _instance;
  10. Dio getClient(String baseUrl,
  11. {BaseOptions newOptions, List<Interceptor> interceptors}) {
  12. if (baseUrl == null || baseUrl.isEmpty) {
  13. throw Exception('baseUrl not be allowed null');
  14. }
  15. Dio client = _mClientMap[baseUrl];
  16. if (client != null) {
  17. if (interceptors != null) {
  18. client.interceptors.addAll(interceptors);
  19. }
  20. return client;
  21. }
  22. client = _createDioClient(baseUrl, options: newOptions);
  23. if (interceptors != null) {
  24. client.interceptors.addAll(interceptors);
  25. }
  26. _mClientMap[baseUrl] = client;
  27. return client;
  28. }
  29. Dio _createDioClient(String baseUrl, {BaseOptions options}) {
  30. if (options == null) {
  31. options = createOptions(baseUrl);
  32. }
  33. return Dio(options);
  34. }
  35. static BaseOptions createOptions(String baseUrl,
  36. {Map<String, dynamic> headers, Map<String, dynamic> queryParameters}) {
  37. return BaseOptions(
  38. connectTimeout: Duration(milliseconds: _DEFAULT_CONNECT_TIMEOUT),
  39. sendTimeout: Duration(milliseconds: _DEFAULT_SEND_TIMEOUT),
  40. receiveTimeout: Duration(milliseconds: _DEFAULT_RECEIVE_TIMEOUT),
  41. baseUrl: baseUrl,
  42. responseType: ResponseType.json,
  43. validateStatus: (status) {
  44. return true;
  45. },
  46. headers: headers,
  47. queryParameters: queryParameters,
  48. );
  49. }
  50. void release() {
  51. _mClientMap.clear();
  52. }
  53. }