Last active
July 22, 2019 08:49
-
-
Save MaySnow/4d1aff151ecdba030f53f03ae1919f91 to your computer and use it in GitHub Desktop.
#flutter dio封装,添加公用header,以及公用配置
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "package:dio/dio.dart"; | |
import 'package:my_demo/utils/config.dart'; | |
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; | |
class HttpUtil { | |
static final HttpUtil _instance = HttpUtil._internal(); | |
Dio _client; | |
FlutterSecureStorage _storage; | |
Dio dio; | |
factory HttpUtil() => _instance; | |
HttpUtil._internal() { | |
if (null == _storage) { | |
_storage = FlutterSecureStorage(); | |
} | |
if (null == _client) { | |
_client = Dio(); | |
_client.options.baseUrl = Config.apiHost; | |
_client.options.receiveTimeout = 1000 * 10; //10秒 | |
_client.options.connectTimeout = 5000; //5秒 | |
_client.interceptors.add(InterceptorsWrapper( | |
onRequest:(RequestOptions options) async { | |
// 在请求被发送之前做一些事情 | |
options.headers['authorization'] = await _storage.read(key: 'token'); | |
print('send request:path:${options.path},baseURL:${options.baseUrl},data:${options.data},queryParameters:${options.queryParameters}'); | |
return options; //continue | |
// 如果你想完成请求并返回一些自定义数据,可以返回一个`Response`对象或返回`dio.resolve(data)`。 | |
// 这样请求将会被终止,上层then会被调用,then中返回的数据将是你的自定义数据data. | |
// | |
// 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象,或返回`dio.reject(errMsg)`, | |
// 这样请求将被中止并触发异常,上层catchError会被调用。 | |
} | |
)); | |
dio = _client; | |
} | |
} | |
} | |
// 使用 | |
Response jsonImgList = await HttpUtil().dio.get( | |
'/api/img/list', | |
queryParameters: { | |
'limit': limit, | |
'page': page | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment