| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- import 'package:dio/dio.dart';
- import 'config.dart'; //用于配置公用常量
- import 'session.dart';
- class Http {
- static Http instance;
- static String token;
- static Config _config = Config();
- static Dio _dio;
- BaseOptions _options;
- static Http getInstance() {
- print("getInstance");
- if (instance == null) {
- instance = new Http();
- }
- }
- Http() {
- // 初始化 Options
- _options = BaseOptions(
- baseUrl: _config.baseUrl,
- connectTimeout: _config.connectTimeout,
- receiveTimeout: _config.receiveTimeout,
- headers: {
-
- }
- );
- _dio = new Dio(_options);
- // //发送请求拦截处理,例如:添加token使用
- _dio.interceptors.add(InterceptorsWrapper(
- onRequest: (RequestOptions options) {
- getKey('token').then((value){
- if(value!=null){
- options.headers = {
- "token":value
- };
- }
- return options; //continue
- });
- },
- onResponse: (Response response) {
- return response;
- },
- onError: (DioError e) {
- print(e);
- return e; //continue
- }
- ));
- }
- // get 请求封装
- get(url, {
- options,
- cancelToken,
- data = null
- }) async {
- //print('get:::url:$url ,body: $data');
- Response response;
- try {
- response = await _dio.get(
- url,
- queryParameters: data,
- cancelToken: cancelToken
- );
- }
- on DioError
- catch (e) {
- if (CancelToken.isCancel(e)) {
- print('get请求取消! ' + e.message);
- } else {
- print('get请求发生错误:$e');
- }
- }
- //print(response);
- return response.data;
- }
- // post请求封装
- post(url, {
- options,
- cancelToken,
- data = null
- }) async {
- //print('post请求::: url:$url ,body: $data');
- Response response;
- try {
- response = await _dio.post(
- url,
- data: data != null ? data : {},
- cancelToken: cancelToken
- );
- }
- on DioError
- catch (e) {
- if (CancelToken.isCancel(e)) {
- print('post请求取消! ' + e.message);
- } else {
- print('post请求发生错误:$e');
- }
- }
- //print(response);
- return response.data;
- }
- }
|