Browse Source

移除API

更新NetUtil token问题
修复非200状态码无法获取数据问题
tags/0.0.1
Weller 4 years ago
parent
commit
49b2912b35
5 changed files with 21 additions and 313 deletions
  1. +0
    -18
      example/lib/main.dart
  2. +0
    -252
      lib/util/api.dart
  3. +19
    -40
      lib/util/net_util.dart
  4. +2
    -2
      lib/util/router_util.dart
  5. +0
    -1
      lib/zhiying_comm.dart

+ 0
- 18
example/lib/main.dart View File

@@ -126,24 +126,6 @@ class HomePage extends StatelessWidget {
}, },
child: Text('测试接口'), child: Text('测试接口'),
), ),
RaisedButton(
onPressed: () async {
Api api = Api('/api/v1/user/info', method: NetMethod.GET);

// api.onCache().then((cache) {
// print('读取缓存 ${cache.toString()}');
// return api.onRequest();
// }).then((result) {
// print('网络请求 ${result.toString().length}');
// }).catchError((error) {
// print('aaaa');
// print('error: ${error.toString()}');
// });
var cache = await api.onCache();
var result = await api.onRequest();
},
child: Text('新网络请求'),
),
RaisedButton( RaisedButton(
onPressed: () { onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) { Navigator.push(context, MaterialPageRoute(builder: (_) {


+ 0
- 252
lib/util/api.dart View File

@@ -1,252 +0,0 @@
import 'dart:convert';
import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'global_config.dart';
import 'shared_prefe_util.dart';

class Api {
final String path;
Map<String, dynamic> params;
final NetMethod method;

static Dio _dio;
static get _net async {
if (_dio == null) {
var setting = await NativeUtil.getSetting();
String domain = setting['domain']; //'http://www.hairuyi.com/';
_config(domain, proxyUrl: '192.168.0.112:8888');
}
return _dio;
}

Api(this.path, {this.params, this.method = NetMethod.POST}) {
this.params = params ?? {};
}

Future<Map> onCache() async {
String cacheKey = getRequestParamsCachedKey(params, path);
// 读取缓存
Map<String, dynamic> cacheMap =
await SharedPreferencesUtil.getNetCacheResult(cacheKey);

if (!EmptyUtil.isEmpty(cacheMap) &&
cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
!EmptyUtil.isEmpty(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
return cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
}
return {};
}

Future<Map> onRequest() async {
Map result = {};

try {
Dio net = await _net;
Map<String, String> headers = await _getHeaders();
var responds = await net.request(path,
data: params,
options: Options(method: enumToString(method), headers: headers));

result = responds.data is Map ? responds.data : jsonDecode(responds.data);

String cacheKey = getRequestParamsCachedKey(params, path);
_setCallBackCacheData(cacheKey,
responds.data is Map ? jsonEncode(responds.data) : responds.data);
} on DioError catch (e) {
_formatError(e);
return {};
}

return result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
}

// 获取headers,headers保存各种签名认证信息
Future<Map<String, String>> _getHeaders() async {
Map<String, String> headers = Map();
headers['device'] = 'wx_applet';
headers['Platform'] = 'wx_applet';

// token 读取SP缓存中的用户token
String token = await SharedPreferencesUtil.getStringValue(
GlobalConfig.SHARED_KEY_TOKEN) ??
'';
const bool inProduction = const bool.fromEnvironment("dart.vm.product");
if (!inProduction && token != '') {
token = 'dda64038e024307436aae390d1242ceaba89040d';
}

if (token != null && token != '') {
headers['token'] = token;
}
return headers;
}

/// 配置网络请求,基础地址,代理地址,如:192.168.0.123:8888(代理地址生产环境无效)
/// apiVersion 接口版本
static void _config(String baseUrl, {String proxyUrl}) {
_dio = Dio(BaseOptions(
method: "post",
baseUrl: baseUrl,
connectTimeout: 15000,
receiveTimeout: 15000,
contentType: Headers.jsonContentType,
followRedirects: true,
));
_dio.interceptors.add(_NetInterceptors());
// _dio.interceptors.add(LogInterceptor());

const bool inProduction = const bool.fromEnvironment("dart.vm.product");
if (proxyUrl != null && proxyUrl != '' && !inProduction) {
_setProxy(proxyUrl);
}
}

/// 设置代理
static void _setProxy(String proxyUrl) {
(_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
client.findProxy = (uri) {
return "PROXY $proxyUrl";
};
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
};
}

/// 获取请求缓存成功的数据
static Future<void> _onCallBackCacheData(
OnCache onCache, String cacheKey) async {
// 读取缓存
Map<String, dynamic> cacheMap =
await SharedPreferencesUtil.getNetCacheResult(cacheKey);

if (!EmptyUtil.isEmpty(cacheMap) &&
cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
!EmptyUtil.isEmpty(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
onCache(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
return;
}
return;
}

/// 缓存请求成功的数据
static void _setCallBackCacheData(String cacheKey, String value) async {
SharedPreferencesUtil.setNetCacheResult(cacheKey, value);
}

/// 根据请求参数,获取缓存的数据
static Future<dynamic> getRequestCachedData(String url,
{Map<String, dynamic> params}) async {
Map<String, dynamic> cacheMap =
await SharedPreferencesUtil.getNetCacheResult(
getRequestParamsCachedKey(params, url));
if (!EmptyUtil.isEmpty(cacheMap) &&
cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
!EmptyUtil.isEmpty(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
return cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
}
return null;
}

/// 判断后台返回是否成功
static bool isSuccess(Map<String, dynamic> data) {
try {
if (!EmptyUtil.isEmpty(data) &&
(data[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
data[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}')) {
return true;
}
} catch (e) {
return false;
}
return false;
}

/// 根据请求参数,获取缓存的Key
static String getRequestParamsCachedKey(
Map<String, dynamic> map, String path) {
if (EmptyUtil.isEmpty(map)) {
return EncodeUtil.generateMd5(path);
}
return EncodeUtil.generateMd5(path + map.toString());
}

/// 签名
static String signWithArray(List<String> params) {
// 字母升序
params.sort();
String result = "";
// result += secret_key;
params.forEach((param) {
result += param;
});
// result += secret_key;
return EncodeUtil.generateMd5(result);
}

/*
* error统一处理
*/
static void _formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
Logger.error('连接超时: ${e.toString()}');
} else if (e.type == DioErrorType.SEND_TIMEOUT) {
Logger.error('请求超时: ${e.toString()}');
} else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
Logger.error('响应超时: ${e.toString()}');
} else if (e.type == DioErrorType.RESPONSE) {
Logger.error('出现异常: ${e.toString()}');
} else if (e.type == DioErrorType.CANCEL) {
Logger.error('请求取消: ${e.toString()}');
} else {
Logger.error('未知错误: ${e.toString()}');
}
}
}

/**
* @description: 网络请求拦截器
* @param {type}
* @return:
*/
class _NetInterceptors extends InterceptorsWrapper {
@override
Future onRequest(RequestOptions options) {
Logger.net(options?.uri?.toString(), data: options.data.toString());
// TODO 加密?
return super.onRequest(options);
}

@override
Future onResponse(Response response) {
Logger.endNet(response?.request?.uri?.toString(),
data: response?.data?.toString() ?? '');
// TODO 解密?
return super.onResponse(response);
}

@override
Future onError(DioError err) {
// Logger.error(err);
return super.onError(err);
}
}

+ 19
- 40
lib/util/net_util.dart View File

@@ -56,14 +56,16 @@ class NetUtil {
/// apiVersion 接口版本 /// apiVersion 接口版本
void _config(String baseUrl, {String proxyUrl}) { void _config(String baseUrl, {String proxyUrl}) {
_dio = Dio(BaseOptions( _dio = Dio(BaseOptions(
method: "post",
baseUrl: baseUrl,
connectTimeout: 15000,
receiveTimeout: 15000,
contentType: Headers.jsonContentType,
followRedirects: true,
headers: {'device': 'wx_applet', 'Platform': 'wx_applet'},
));
method: "post",
baseUrl: baseUrl,
connectTimeout: 15000,
receiveTimeout: 15000,
contentType: Headers.jsonContentType,
followRedirects: true,
headers: {'device': 'wx_applet', 'Platform': 'wx_applet'},
validateStatus: (_) {
return true;
}));
_dio.interceptors.add(_NetInterceptors()); _dio.interceptors.add(_NetInterceptors());
// _dio.interceptors.add(LogInterceptor()); // _dio.interceptors.add(LogInterceptor());


@@ -100,9 +102,14 @@ class NetUtil {


Response response; Response response;
try { try {
String token = await SharedPreferencesUtil.getStringValue(
GlobalConfig.SHARED_KEY_TOKEN) ??
'';
Dio dio = await NetUtil.getInstance().dio; Dio dio = await NetUtil.getInstance().dio;
response = await dio.request(path, response = await dio.request(path,
data: sign, options: Options(method: enumToString(method)));
data: sign,
options:
Options(method: enumToString(method), headers: {'token': token}));
} on DioError catch (e) { } on DioError catch (e) {
_formatError(e); _formatError(e);
} }
@@ -137,7 +144,6 @@ class NetUtil {
static void request(String path, static void request(String path,
{NetMethod method = NetMethod.GET, {NetMethod method = NetMethod.GET,
Map<String, dynamic> params, Map<String, dynamic> params,
Map<String, File> multiFiles,
OnSuccess onSuccess, OnSuccess onSuccess,
OnError onError, OnError onError,
OnCache onCache}) async { OnCache onCache}) async {
@@ -152,39 +158,12 @@ class NetUtil {
await _onCallBackCacheData(onCache, cacheKey); await _onCallBackCacheData(onCache, cacheKey);
} }


// 参数签名
Map<String, dynamic> sign = await signParams(params);

Response response;
try {
// token 读取SP缓存中的用户token
String token = await SharedPreferencesUtil.getStringValue(
GlobalConfig.SHARED_KEY_TOKEN) ??
'';

const bool inProduction = const bool.fromEnvironment("dart.vm.product");
if (!inProduction && token != '') {
token = 'dda64038e024307436aae390d1242ceaba89040d';
}
Dio dio = await NetUtil.getInstance().dio;
response = await dio.request(path,
data: sign,
options:
Options(method: enumToString(method), headers: {'token': token}));
} on DioError catch (e) {
_formatError(e);
}

try { try {
var result =
response.data is Map ? response.data : jsonDecode(response.data);
Map result = await NetUtil.post(path, method: method, params: params);
// TODO 解密? // TODO 解密?
if (isSuccess(result)) { if (isSuccess(result)) {
if (onSuccess != null) { if (onSuccess != null) {
onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]); onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
// 缓存返回的数据
_setCallBackCacheData(cacheKey,
response.data is Map ? jsonEncode(response.data) : response.data);
} }
return; return;
} }
@@ -198,8 +177,8 @@ class NetUtil {
if (onError != null) { if (onError != null) {
onError(!EmptyUtil.isEmpty(result) onError(!EmptyUtil.isEmpty(result)
? !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]) ? !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG])
? result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]
: '未知错误'
? result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]
: '未知错误'
: '未知错误'); : '未知错误');
} }
} catch (e) { } catch (e) {


+ 2
- 2
lib/util/router_util.dart View File

@@ -34,9 +34,9 @@ class RouterUtil {
if (PageFactory.hasRegisted(skipModel.skipIdentifier)) { if (PageFactory.hasRegisted(skipModel.skipIdentifier)) {
page = PageFactory.create(skipModel.skipIdentifier, data); page = PageFactory.create(skipModel.skipIdentifier, data);
} else { } else {
Api api = Api('/api/v1/mod/${skipModel.skipIdentifier.toString()}',
var result = await NetUtil.post(
'/api/v1/mod/${skipModel.skipIdentifier.toString()}',
method: NetMethod.GET); method: NetMethod.GET);
var result = await api.onRequest();
Logger.debug(result); Logger.debug(result);
page = PageFactory.create('index', Map<String, dynamic>.from(result)); page = PageFactory.create('index', Map<String, dynamic>.from(result));
} }


+ 0
- 1
lib/zhiying_comm.dart View File

@@ -11,7 +11,6 @@ export 'models/user/user_info_model_notifier.dart';
export 'models/user/user_info_model_notifier.dart'; export 'models/user/user_info_model_notifier.dart';
export 'native/native_router.dart'; export 'native/native_router.dart';
export 'pages/empty_page.dart'; export 'pages/empty_page.dart';
export 'util/api.dart';
export 'util/defalut_widget_creater.dart'; export 'util/defalut_widget_creater.dart';
export 'util/empty_util.dart'; export 'util/empty_util.dart';
export 'util/encode_util.dart'; export 'util/encode_util.dart';


Loading…
Cancel
Save