在Flutter开发过程中势必要用到网络请求,在Flutter插件库中有Http、Dio等很多优秀的框架,个人比较喜欢用Dio请求框架
在此总结下自己的封装经验
Dio对象在App请求中一般使用一个,如有特殊需求会使用多个,在此使用单例模式。
import 'package:dio/dio.dart';
import 'package:loxen/api/intercept.dart';
import 'package:loxen/utils/config.dart';
class BaseNetWork {
// 工厂模式
factory BaseNetWork() => _getInstance();
static BaseNetWork get instance => _getInstance();
static BaseNetWork _instance;
Dio dio;
BaseOptions options;
BaseNetWork._internal() {
dio = Dio()
..options = BaseOptions(
baseUrl: Constants.BASE_URL,
connectTimeout: 10000,
receiveTimeout: 1000 * 60 * 60 * 24,
responseType: ResponseType.json,
headers: {"Content-Type": "application/json"})
//网络状态拦截
..interceptors.add(AuthInterceptor())
..interceptors.add(HttpLog())
..interceptors.add(ErrorInterceptor());
}
static BaseNetWork _getInstance() {
if (_instance == null) {
_instance = new BaseNetWork._internal();
}
return _instance;
}
}
这里对创建Dio对象,进行了些基础配置,添加了些请求拦截器
AuthInterceptor:主要作用在请求内加入http中header的信息:
class AuthInterceptor extends Interceptor {
@override
Future onRequest(RequestOptions options) async {
String accessToken = await SharedPreferencesUtil.getData(Constants.ACCESS_TOKEN);
if (accessToken != null && accessToken != '') {
options.headers['content-type'] = 'application/json;charset=utf-8';
options.headers['Authorization'] = 'JWT $accessToken';
}
return super.onRequest(options);
}
}
HttpLog:是对请求过程中的参数和返回值参数进行打印:
class HttpLog extends Interceptor{
@override
Future onRequest(RequestOptions options) {
print("\n ---------Start Http Request---------");
print("Request_BaseUrl:${options.baseUrl}");
print("Request_Path:${options.path}");
print("Request_Method:${options.method}");
print("Request_Headers:${options.headers}");
print("Request_Data:${options.data}");
print("Request_QueryParameters:${options.queryParameters}");
print("---------End Http Request---------");
return super.onRequest(options);
}
@override
Future onResponse(Response response) {
print("---------Start Http Response---------");
print("Response_BaseUrl:${response.request.baseUrl}");
print("Response_Path:${response.request.path}");
print("Response_StatusCode:${response.statusCode}");
print("Response_StatusMessage:${response.statusMessage}");
print("Response_Headers:${response.headers.toString()}");
print("---------End Http Response---------");
return super.onResponse(response);
}
}
ErrorInterceptor:这里是对登录的Token做了些刷新处理
class ErrorInterceptor extends Interceptor {
@override
onError(DioError error) async {
print(error);
//判读异常状态 401未登录过期或者未登录状态的异常
if (error.response != null && error.response.statusCode == 401) {
String token = await SharedPreferencesUtil.getData(Constants.ACCESS_TOKEN);//获取本地存储的Token
if (token != null && token.trim() != '') {//Token存在则说明Token过期需要刷新,否则是未登录状态不做处理
Dio dio = BaseNetWork.instance.dio;//获取应用的Dio对象进行锁定 防止后面请求还是未登录状态下请求
dio.lock();
String accessToken = await getToken();//重新获取Token
dio.unlock();
if (accessToken != '') {
Dio tokenDio2 = new Dio(BaseNetWork.instance.dio.options); //创建新的Dio实例
var request = error.request;
request.headers['Authorization'] = 'JWT $accessToken';
var response = await tokenDio2.request(request.path,
data: request.data,
queryParameters: request.queryParameters,
cancelToken: request.cancelToken,
options: request,
onReceiveProgress: request.onReceiveProgress);
return response;
}
}
}
super.onError(error);
}
Future<String> getToken() async {
//获取当前的refreshToken,一般后台会在登录后附带一个刷新Token用的reToken
String refreshToken =
await SharedPreferencesUtil.getData(Constants.REFRESH_TOKEN);
//因为App单例的Dio对象已被锁定,所以需要创建新的Dio实例
Dio tokenDio = new Dio(BaseNetWork.instance.dio.options);
Map<String, String> map = {
"rft": refreshToken,
}; //设置当前的refreshToken
try {
//发起请求,获取Token
var response = await tokenDio.post("/api/v1/user/refresh_token", data: map);
if (response.statusCode == 201) {
LoginBean loginbean = LoginBean.fromJson(response.data);
SharedPreferencesUtil.putData(Constants.ACCESS_TOKEN, loginbean.data.token);
if (loginbean.data.rft != null && loginbean.data.rft.trim() != '') {
SharedPreferencesUtil.putData(Constants.REFRESH_TOKEN, loginbean.data.rft);
}
return loginbean.data.token;
}
return '';
} on DioError catch (e) {
print("Token刷新失败:$e");
SharedPreferencesUtil.putData(Constants.ACCESS_TOKEN, '');
SharedPreferencesUtil.putData(Constants.REFRESH_TOKEN, '');
return '';
}
}
}
之后就可以通过单例对象直接调用Dio对象发起 请求。
后面则需要将我们业务所需的ApiUrl在进行一次调用封装,返回值解析等等操作,在操作Dio过程中将业务和UI逻辑进行很好的分离。
mixin LikeMixin {
Stream<LikeList> userLikes(
{String userId = '0', String page = '1', String pageSize}) {
return ApiService.userLikes(userId, page, pageSize)
.flatMap((value) => compute(decodeLikeList, value.data).asStream())
.flatMap((value) => Stream.value(value.data));
}
Stream<int> likeComment(String id) {
return ApiService.likeComment(id)
.flatMap((value) => Stream.value(value.statusCode));
}
Stream<int> unLikeComment(String id) {
return ApiService.unLikeComment(id)
.flatMap((value) => Stream.value(value.statusCode));
}
Stream<Like> like(String type, String id) {
return ApiService.likeSomething(type, id)
.flatMap((value) => compute(decodeLikeBean, value.data).asStream())
.flatMap((value) => Stream.value(value.data));
}
Stream<Like> unLike(String type, String id) {
return ApiService.unLikeSomething(type, id)
.flatMap((value) => compute(decodeLikeBean, value.data).asStream())
.flatMap((value) => Stream.value(value.data));
}
static BaseMode<LikeList> decodeLikeList(dynamic json) {
return BaseMode<LikeList>(json);
}
static BaseMode<Like> decodeLikeBean(dynamic json) {
return BaseMode<Like>(json);
}
}