request.dart 2.2 KB

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