request.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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');
  68. }
  69. }
  70. //print(response);
  71. return response.data;
  72. }
  73. // post请求封装
  74. post(url, {
  75. options,
  76. cancelToken,
  77. data = null
  78. }) async {
  79. //print('post请求::: url:$url ,body: $data');
  80. Response response;
  81. try {
  82. response = await _dio.post(
  83. url,
  84. data: data != null ? data : {},
  85. cancelToken: cancelToken
  86. );
  87. }
  88. on DioError
  89. catch (e) {
  90. if (CancelToken.isCancel(e)) {
  91. print('post请求取消! ' + e.message);
  92. } else {
  93. print('post请求发生错误:$e');
  94. }
  95. }
  96. //print(response);
  97. return response.data;
  98. }
  99. }