以下有dialog 自行删除或者适应添加
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:fl_wuliu/common/app_global.dart';
import 'package:fl_wuliu/common/event/http_error_event.dart';
import 'package:fl_wuliu/http/error_back_msg.dart';
import 'package:fl_wuliu/http/request_manager.dart';
import 'package:fl_wuliu/utils/tire_export.dart';
import 'package:fl_wuliu/dialog/simple_dialog.dart' as dialog;
/*
* 网络请求管理类
*/
class DioManager {
//写一个单例
//在 Dart 里,带下划线开头的变量是私有变量
static DioManager _instance;
static BuildContext _buildContext;
static DioManager getInstance({BuildContext buildContext}) {
_buildContext = buildContext;
if (_instance == null) {
_instance = DioManager();
}
return _instance;
}
Dio dio = new Dio();
static get currentTime => DateTime.now().millisecondsSinceEpoch ?? '';
Map headers = {
"content-type": "application/json",
"appId": "6",
"platformId": "2",
"token": Global.user.getToken(),
"timestamp": currentTime.toString(),
"sign": "FF6ED57983248E3701EE97F3F23A41F9",
};
DioManager() {
// Set default configs
dio.options.headers = headers;
dio.options.connectTimeout = 5000;
dio.options.receiveTimeout = 3000;
dio.options.responseType = ResponseType.json;
dio.interceptors.add(LogInterceptor(responseBody: Global.isDebug)); //是否开启请求日志
dio.interceptors.add(CookieManager(CookieJar())); //缓存相关类,具体设置见https://github.com/flutterchina/cookie_jar
}
//get请求
get(String url, Map params, Function successCallBack, {errorCallBack}) async {
_requstHttp(Global.getBaseUrl() + url, successCallBack, errorCallBack, 'get', params);
}
//post请求
post(String url, Map params, Function successCallBack, {errorCallBack}) async {
_requstHttp(Global.getBaseUrl() + url, successCallBack, errorCallBack, "post", params);
}
_requstHttp(String url, Function successCallBack, [errorCallBack, String method, Map params]) async {
if (_buildContext != null) {
dialog.showSimpleLoadingDialog(context: _buildContext, msg: "请求中");
}
Response response;
try {
if (method == 'get') {
//get请求 拼接参数放queryParameters里面
if (params != null && params.isNotEmpty) {
response = await dio.get(url, queryParameters: params);
} else {
response = await dio.get(url);
}
} else if (method == 'post') {
//post请求 对象放data里面
if (params != null && params.isNotEmpty) {
response = await dio.post(url, data: params);
} else {
response = await dio.post(url);
}
}
} on DioError catch (error) {
if (_buildContext != null) {
dialog.dismissDialog(_buildContext);
errorCallBack();
}
// 请求错误处理
Response errorResponse;
if (error.response != null) {
errorResponse = error.response;
} else {
errorResponse = new Response(statusCode: 666);
}
// 请求超时
if (error.type == DioErrorType.CONNECT_TIMEOUT || error.type == DioErrorType.RESPONSE) {
errorResponse.statusCode = ResultCode.CONNECT_TIMEOUT;
ToastOk.show(msg: "请求已超时,稍后重试");
errorCallBack();
}
// 一般服务器错误
else if (error.type == DioErrorType.RECEIVE_TIMEOUT) {
errorResponse.statusCode = ResultCode.RECEIVE_TIMEOUT;
}
return '';
}
// debug模式打印相关数据
if (Global.isDebug) {
JsonUtil.printRespond(response);
}
if (successCallBack != null) {
try {
ErrorBackMsg errorBackMsg = ErrorBackMsg.fromJson(json.decode(response.toString()));
if (errorBackMsg.code != 0) {
if (_buildContext != null) {
dialog.dismissDialog(_buildContext);
}
if (errorBackMsg.code == 10010002) {
ToastOk.show(msg: "登录异常,请重新登录");
HttpEvent.eventHandleFunction("logout");
} else {
ToastOk.show(msg: errorBackMsg.msg ?? "请求异常,稍后重试");
}
errorCallBack();
} else {
if (_buildContext != null) {
dialog.dismissDialog(_buildContext);
}
successCallBack(response);
}
} catch (e) {
print("异常${e}");
errorCallBack();
if (_buildContext != null) {
dialog.dismissDialog(_buildContext);
}
}
}
}
}
class JsonUtil {
//带有首行缩进的Json格式
static JsonEncoder encoder = JsonEncoder.withIndent(' ');
/// 单纯的Json格式输出打印
static void printJson(Object object) {
try {
var encoderString = encoder.convert(object);
// print(encoderString);
// 不使用print()方法是因为这是单条输出,如果过长无法显示全
// 所以使用debugPrint()
debugPrint(encoderString);
// 下面这语句的效果与debugPrint 相同
//prettyString.split('\n').forEach((element) => print(element));
} catch (e) {
print(e);
}
}
/// 接收Dio请求库返回的Response对象
static void printRespond(Response response) {
Map httpLogMap = Map();
httpLogMap.putIfAbsent("requestUrl", () => "${response.request.uri}");
httpLogMap.putIfAbsent("requestHeaders", () => response.request.headers);
httpLogMap.putIfAbsent("requestQueryParameters", () => response.request.queryParameters);
httpLogMap.putIfAbsent("requestPostdata", () => response.request.data);
httpLogMap.putIfAbsent("respondData", () => response.data);
printJson(httpLogMap);
}
}
/*
* dio网络请求失败的回调错误码
*/
class ResultCode {
//正常返回是1
static const SUCCESS = 1;
//异常返回是0
static const ERROR = 1;
/// When opening url timeout, it occurs.
static const CONNECT_TIMEOUT = 401;
///It occurs when receiving timeout.
static const RECEIVE_TIMEOUT = -2;
/// When the server response, but with a incorrect status, such as 404, 503...
static const RESPONSE = -3;
/// When the request is cancelled, dio will throw a error with this type.
static const CANCEL = -4;
/// read the DioError.error if it is not null.
static const DEFAULT = -5;
}
例子使用
DioManager.getInstance(buildContext: context).post(ApiUrls.getPhoneCode, {"logisticsNo": widget?.subOrderId ?? ""},
(data) {
BaseBoolEntity.fromJson(json.decode(data.toString())).data
? ToastOk.show(msg: "获取验证码成功")
: ToastOk.show(msg: "操作失败,稍后重试");
},errorCallBack: (){});