Commit code. Update time: 2023-06-25
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
/*后台接口api*/
|
||||
import 'package:sail/common/public.dart';
|
||||
|
||||
class Apis {
|
||||
static String appid = "IPOSih2134KHJKLDIO";
|
||||
static String token =
|
||||
"${Global.baseUrl}flutter/gettoken.php/?s=App.JYApp_Main.GetToken";
|
||||
static String getLaunchAds =
|
||||
"${Global.baseUrl}flutter/gettoken.php/?s=App.JYApp_Main.GetLaunchAds";
|
||||
static String getRecommandList = "${Global.baseUrl}flutter/recommand.php";
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'http_exceptions.dart';
|
||||
|
||||
class ApiResponse<T> implements Exception {
|
||||
Status status;
|
||||
T? data;
|
||||
DioHttpException? exception;
|
||||
|
||||
/**
|
||||
* 成功 网络请求
|
||||
*/
|
||||
ApiResponse.completed(this.data) : status = Status.COMPLETED;
|
||||
|
||||
/**
|
||||
* 错误 网络请求
|
||||
*/
|
||||
ApiResponse.error(this.exception) : status = Status.ERROR;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return "Status : $status \n Message : $exception \n Data : $data";
|
||||
}
|
||||
}
|
||||
|
||||
enum Status { COMPLETED, ERROR }
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'http_exceptions.dart';
|
||||
|
||||
/// 错误处理拦截器
|
||||
class ErrorInterceptor extends Interceptor {
|
||||
Duration durationTime = Duration(seconds: 2);
|
||||
|
||||
@override
|
||||
onError(DioError err, ErrorInterceptorHandler handler) {
|
||||
// error统一处理
|
||||
DioHttpException appException = DioHttpException.create(err);
|
||||
// 错误提示
|
||||
print('DioError===: ${appException.toString()}');
|
||||
err.error = appException;
|
||||
super.onError(err, handler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import 'dart:async';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:sail/common/public.dart';
|
||||
import 'error_interceptor.dart';
|
||||
|
||||
class Http {
|
||||
///超时时间
|
||||
static const int CONNECT_TIMEOUT = 30000;
|
||||
static const int RECEIVE_TIMEOUT = 30000;
|
||||
|
||||
static Http _instance = Http._internal();
|
||||
|
||||
factory Http() => _instance;
|
||||
|
||||
Dio? dio;
|
||||
CancelToken _cancelToken = new CancelToken();
|
||||
|
||||
Http._internal() {
|
||||
if (dio == null) {
|
||||
// BaseOptions、Options、RequestOptions 都可以配置参数,优先级别依次递增,且可以根据优先级别覆盖参数
|
||||
BaseOptions options = new BaseOptions(
|
||||
connectTimeout: CONNECT_TIMEOUT,
|
||||
// 响应流上前后两次接受到数据的间隔,单位为毫秒。
|
||||
receiveTimeout: RECEIVE_TIMEOUT,
|
||||
headers: {},
|
||||
);
|
||||
if (options.contentType != null &&
|
||||
options.headers.containsKey(Headers.contentTypeHeader)) {
|
||||
options.headers.remove(Headers.contentTypeHeader);
|
||||
}
|
||||
dio = new Dio(options);
|
||||
|
||||
// 添加拦截器
|
||||
dio!.interceptors.add(ErrorInterceptor());
|
||||
dio!.interceptors.add(LogInterceptor());
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取本地配置
|
||||
Future<Map<String, dynamic>?> getAuthorizationHeader() async {
|
||||
var headers;
|
||||
String? accessToken = SpUtil.getString("SP_TOKEN", defValue: null);
|
||||
if (accessToken != null) {
|
||||
int expiresM = SpUtil.getInt("SP_EXPIRES_M");
|
||||
// token过期(有5分钟缓冲时间),刷新token
|
||||
if (DateTime.now().millisecondsSinceEpoch > expiresM) {
|
||||
// accessToken = await Auth.refreshToken();
|
||||
}
|
||||
headers = {"Authorization": 'Bearer $accessToken'};
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
///初始化公共属性
|
||||
///
|
||||
/// [baseUrl] 地址前缀
|
||||
/// [connectTimeout] 连接超时赶时间
|
||||
/// [receiveTimeout] 接收超时赶时间
|
||||
/// [interceptors] 基础拦截器
|
||||
void init(
|
||||
{String? baseUrl,
|
||||
int? connectTimeout,
|
||||
int? receiveTimeout,
|
||||
List<Interceptor>? interceptors}) {
|
||||
dio!.options = dio!.options.copyWith(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: connectTimeout,
|
||||
receiveTimeout: receiveTimeout,
|
||||
);
|
||||
if (interceptors != null && interceptors.isNotEmpty) {
|
||||
dio!.interceptors.addAll(interceptors);
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置headers
|
||||
void setHeaders(Map<String, dynamic> map) {
|
||||
dio!.options.headers.addAll(map);
|
||||
}
|
||||
|
||||
/*
|
||||
* 取消请求
|
||||
*
|
||||
* 同一个cancel token 可以用于多个请求,当一个cancel token取消时,所有使用该cancel token的请求都会被取消。
|
||||
* 所以参数可选
|
||||
*/
|
||||
void cancelRequests({CancelToken? token}) {
|
||||
token ?? _cancelToken.cancel("cancelled");
|
||||
}
|
||||
|
||||
/// restful get 操作
|
||||
Future get(
|
||||
String path, {
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
bool refresh = false,
|
||||
String? cacheKey,
|
||||
bool cacheDisk = false,
|
||||
bool withoutToken = false,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
requestOptions = requestOptions.copyWith(extra: {
|
||||
"refresh": refresh,
|
||||
"cacheKey": cacheKey,
|
||||
"cacheDisk": cacheDisk,
|
||||
});
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
Map<String, dynamic>? headers = requestOptions.headers;
|
||||
if (_authorization != null &&
|
||||
(headers == null || headers["Authorization"] == null) &&
|
||||
!withoutToken) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
Response response;
|
||||
response = await dio!.get(path,
|
||||
queryParameters: params,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/// restful post 操作
|
||||
Future post(
|
||||
String path, {
|
||||
Map<String, dynamic>? params,
|
||||
data,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
if (requestOptions.headers == null ||
|
||||
requestOptions.headers!["Authorization"] == null) {
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
if (_authorization != null) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
}
|
||||
var response = await dio!.post(path,
|
||||
data: data,
|
||||
queryParameters: params,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/// restful put 操作
|
||||
Future put(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
if (_authorization != null &&
|
||||
(requestOptions.headers == null ||
|
||||
requestOptions.headers!["Authorization"] == null)) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
var response = await dio!.put(path,
|
||||
data: data,
|
||||
queryParameters: params,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/// restful patch 操作
|
||||
Future patch(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
if (_authorization != null &&
|
||||
(requestOptions.headers == null ||
|
||||
requestOptions.headers!["Authorization"] == null)) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
var response = await dio!.patch(path,
|
||||
data: data,
|
||||
queryParameters: params,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/// restful delete 操作
|
||||
Future delete(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
if (_authorization != null &&
|
||||
(requestOptions.headers == null ||
|
||||
requestOptions.headers!["Authorization"] == null)) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
var response = await dio!.delete(path,
|
||||
data: data,
|
||||
queryParameters: params,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/// restful post form 表单提交操作
|
||||
Future postForm(
|
||||
String path, {
|
||||
required Map<String, dynamic> data,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
Options requestOptions = options ?? Options();
|
||||
Map<String, dynamic>? _authorization = await getAuthorizationHeader();
|
||||
if (_authorization != null &&
|
||||
(requestOptions.headers == null ||
|
||||
requestOptions.headers!["Authorization"] == null)) {
|
||||
requestOptions = requestOptions.copyWith(headers: _authorization);
|
||||
}
|
||||
var response = await dio!.post(path,
|
||||
data: FormData.fromMap(data),
|
||||
queryParameters: data,
|
||||
options: requestOptions,
|
||||
cancelToken: cancelToken ?? _cancelToken);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// 自定义异常
|
||||
class DioHttpException implements Exception {
|
||||
final String? message;
|
||||
final int? code;
|
||||
|
||||
DioHttpException([
|
||||
this.code,
|
||||
this.message,
|
||||
]);
|
||||
|
||||
String toString() {
|
||||
return "$code$message";
|
||||
}
|
||||
|
||||
factory DioHttpException.create(DioError error) {
|
||||
switch (error.type) {
|
||||
case DioErrorType.other:
|
||||
{
|
||||
// 网络异常
|
||||
return BadRequestException(-2, "无网络");
|
||||
}
|
||||
|
||||
case DioErrorType.cancel:
|
||||
{
|
||||
return BadRequestException(-1, "请求取消");
|
||||
}
|
||||
|
||||
case DioErrorType.connectTimeout:
|
||||
{
|
||||
return BadRequestException(-1, "连接超时");
|
||||
}
|
||||
|
||||
case DioErrorType.sendTimeout:
|
||||
{
|
||||
return BadRequestException(-1, "请求超时");
|
||||
}
|
||||
|
||||
case DioErrorType.receiveTimeout:
|
||||
{
|
||||
return BadRequestException(-1, "响应超时");
|
||||
}
|
||||
|
||||
case DioErrorType.response:
|
||||
{
|
||||
try {
|
||||
int? errCode = error.response!.statusCode;
|
||||
switch (errCode) {
|
||||
case 400:
|
||||
{
|
||||
String? msgOf400;
|
||||
try {
|
||||
msgOf400 = error.response!.data["message"];
|
||||
} on Exception catch (e) {
|
||||
print('****** 400 exception: $e');
|
||||
}
|
||||
return BadRequestException(errCode, msgOf400 ?? "请求语法错误");
|
||||
}
|
||||
|
||||
case 401:
|
||||
{
|
||||
return UnauthorisedException(errCode, "没有权限");
|
||||
}
|
||||
|
||||
case 403:
|
||||
{
|
||||
return UnauthorisedException(errCode, "服务器拒绝执行");
|
||||
}
|
||||
|
||||
case 404:
|
||||
{
|
||||
return UnauthorisedException(errCode, "无法连接服务器");
|
||||
}
|
||||
|
||||
case 405:
|
||||
{
|
||||
return UnauthorisedException(errCode, "请求方法被禁止");
|
||||
}
|
||||
|
||||
case 500:
|
||||
{
|
||||
return UnauthorisedException(
|
||||
errCode, error.response?.statusMessage ?? "服务器内部错误");
|
||||
}
|
||||
|
||||
case 502:
|
||||
{
|
||||
return UnauthorisedException(errCode, "无效的请求");
|
||||
}
|
||||
|
||||
case 503:
|
||||
{
|
||||
return UnauthorisedException(errCode, "服务器挂了");
|
||||
}
|
||||
|
||||
case 505:
|
||||
{
|
||||
return UnauthorisedException(errCode, "不支持HTTP协议请求");
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
return DioHttpException(
|
||||
errCode, error.response?.statusMessage);
|
||||
}
|
||||
}
|
||||
} on Exception catch (_) {
|
||||
return DioHttpException(-1, "未知错误");
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
{
|
||||
return DioHttpException(-1, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求错误
|
||||
class BadRequestException extends DioHttpException {
|
||||
BadRequestException([int? code, String? message]) : super(code, message);
|
||||
}
|
||||
|
||||
/// 未认证异常
|
||||
class UnauthorisedException extends DioHttpException {
|
||||
UnauthorisedException([int? code, String? message]) : super(code, message);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'http.dart';
|
||||
import 'package:sync_http/sync_http.dart';
|
||||
|
||||
class HttpUtils {
|
||||
static void init(
|
||||
{String? baseUrl,
|
||||
int? connectTimeout,
|
||||
int? receiveTimeout,
|
||||
List<Interceptor>? interceptors}) {
|
||||
Http().init(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: connectTimeout,
|
||||
receiveTimeout: receiveTimeout,
|
||||
interceptors: interceptors);
|
||||
}
|
||||
|
||||
static void setHeaders(Map<String, dynamic> map) {
|
||||
Http().setHeaders(map);
|
||||
}
|
||||
|
||||
static void cancelRequests({CancelToken? token}) {
|
||||
Http().cancelRequests(token: token);
|
||||
}
|
||||
|
||||
static Future get(
|
||||
String path, {
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
bool refresh = false,
|
||||
String? cacheKey,
|
||||
bool cacheDisk = false,
|
||||
bool withoutToken = false,
|
||||
}) async {
|
||||
// SyncHttpClient.getUrl(path)
|
||||
return await Http().get(path,
|
||||
params: params,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
refresh: refresh,
|
||||
cacheKey: cacheKey,
|
||||
withoutToken: withoutToken);
|
||||
}
|
||||
|
||||
static Future post(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
return await Http().post(
|
||||
path,
|
||||
data: data,
|
||||
params: params,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
);
|
||||
}
|
||||
|
||||
static Future put(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
return await Http().put(
|
||||
path,
|
||||
data: data,
|
||||
params: params,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
);
|
||||
}
|
||||
|
||||
static Future patch(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
return await Http().patch(
|
||||
path,
|
||||
data: data,
|
||||
params: params,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
);
|
||||
}
|
||||
|
||||
static Future delete(
|
||||
String path, {
|
||||
data,
|
||||
Map<String, dynamic>? params,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
return await Http().delete(
|
||||
path,
|
||||
data: data,
|
||||
params: params,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
);
|
||||
}
|
||||
|
||||
static Future postForm(
|
||||
String path, {
|
||||
required Map<String, dynamic> data,
|
||||
Options? options,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
return await Http().postForm(
|
||||
path,
|
||||
data: data,
|
||||
options: options,
|
||||
cancelToken: cancelToken,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user