request.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import 'package:dio/dio.dart';
  2. import 'config.dart'; //用于配置公用常量
  3. class Http {
  4. static Http instance;
  5. static String token;
  6. static Config _config = Config();
  7. static Dio _dio;
  8. BaseOptions _options;
  9. static Http getInstance() {
  10. print("getInstance");
  11. if (instance == null) {
  12. instance = new Http();
  13. }
  14. }
  15. Http() {
  16. // 初始化 Options
  17. _options = BaseOptions(
  18. baseUrl: _config.baseUrl,
  19. connectTimeout: _config.connectTimeout,
  20. receiveTimeout: _config.receiveTimeout,
  21. headers: {}
  22. );
  23. _dio = new Dio(_options);
  24. // //发送请求拦截处理,例如:添加token使用
  25. _dio.interceptors.add(InterceptorsWrapper(
  26. onRequest: (RequestOptions options) {
  27. // options.headers = {
  28. // token:'123'
  29. // };
  30. return options; //continue
  31. },
  32. onResponse: (Response response) {
  33. return response;
  34. },
  35. onError: (DioError e) {
  36. print(e);
  37. return e; //continue
  38. }
  39. ));
  40. }
  41. // get 请求封装
  42. get(url, {
  43. options,
  44. cancelToken,
  45. data = null
  46. }) async {
  47. print('get:::url:$url ,body: $data');
  48. Response response;
  49. try {
  50. response = await _dio.get(
  51. url,
  52. queryParameters: data,
  53. cancelToken: cancelToken
  54. );
  55. }
  56. on DioError
  57. catch (e) {
  58. if (CancelToken.isCancel(e)) {
  59. print('get请求取消! ' + e.message);
  60. } else {
  61. print('get请求发生错误:$e');
  62. }
  63. }
  64. return response.data;
  65. }
  66. // post请求封装
  67. post(url, {
  68. options,
  69. cancelToken,
  70. data = null
  71. }) async {
  72. print('post请求::: url:$url ,body: $data');
  73. Response response;
  74. try {
  75. response = await _dio.post(
  76. url,
  77. data: data != null ? data : {},
  78. cancelToken: cancelToken
  79. );
  80. }
  81. on DioError
  82. catch (e) {
  83. if (CancelToken.isCancel(e)) {
  84. print('post请求取消! ' + e.message);
  85. } else {
  86. print('post请求发生错误:$e');
  87. }
  88. }
  89. return response.data;
  90. }
  91. }