Commit 81404e31 authored by ouxiang's avatar ouxiang

optimize network

parent 6ab539f6
...@@ -2,8 +2,8 @@ import 'package:dio/dio.dart'; ...@@ -2,8 +2,8 @@ import 'package:dio/dio.dart';
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
class NetWorkSuccess { class NetworkSuccess {
NetWorkSuccess({this.data}); NetworkSuccess({this.data});
final Map data; final Map data;
Map get dataMap{ Map get dataMap{
if (this.data.runtimeType == Map) { if (this.data.runtimeType == Map) {
...@@ -12,8 +12,8 @@ class NetWorkSuccess { ...@@ -12,8 +12,8 @@ class NetWorkSuccess {
} }
} }
class NetWorkError { class NetworkError {
NetWorkError({this.error}); NetworkError({this.error});
final Map error; final Map error;
int get errorCode{ int get errorCode{
if (this.error.runtimeType == Map) { if (this.error.runtimeType == Map) {
...@@ -23,13 +23,19 @@ class NetWorkError { ...@@ -23,13 +23,19 @@ class NetWorkError {
} }
class ALURL { class ALURL {
ALURL({this.host}) : assert(host != null); ALURL({this.api}) : assert(api != null);
final String host; final String api;
static final baseUrl = 'http://earth.igengmei.com'; static final baseUrl = 'http://earth.igengmei.com';
String get originUrl => (baseUrl + host); String get originUrl => (baseUrl + api);
} }
class ALNetWorkHeader { class ALNetworkHeader {
BaseOptions get options{
BaseOptions option = BaseOptions();
option.headers =this.header;
return option;
}
Map<String, dynamic> get header{ Map<String, dynamic> get header{
return { return {
...@@ -65,73 +71,124 @@ class ALNetWorkHeader { ...@@ -65,73 +71,124 @@ class ALNetWorkHeader {
} }
// 管理任务 // 管理任务
class ALNetWorkTask { class ALNetworkTask {
ALNetWorkTask({this.success, this.error, this.url, this.serviceInstance}); ALNetworkTask({this.serviceInstance,this.networkContext, this.response});
final NetWorkSuccessCallback success;
final ALURL url;
final NetWorkErrorCallback error;
final Dio serviceInstance; final Dio serviceInstance;
final ALNetwork networkContext;
Response response;
void cancle() { void cancle(String api) {
// CancelToken
} }
} }
typedef NetWorkSuccessCallback = void Function(NetWorkSuccess success); typedef NetworkSuccessCallback = void Function(NetworkSuccess success);
typedef NetWorkErrorCallback = void Function(NetWorkError error); typedef NetWorkErrorCallback = void Function(NetworkError error);
typedef ProgressCallback = void Function(int count, int total); typedef ProgressCallback = void Function(int count, int total);
class ALNetWork { class ALNetwork {
//static 修饰的变量,为类变量,通过类对象访问 /**
// static final shareInstance = new ALNetWork(); * 任务映射表
//任务映射表 * 外部可以通过 ALNetwork.taskMap 获取
static Map<String, ALNetWorkTask> taskMap = {}; */
static Map<String, ALNetworkTask> taskMap = {};
const ALNetWork( const ALNetwork(
{this.success, {this.success,
this.error, this.error,
this.progress, this.progress,
this.host, this.api,
this.params}) : assert(host != null); this.params,
this.formData}) : assert(api != null);
final NetWorkSuccessCallback success; final NetworkSuccessCallback success;
final NetWorkErrorCallback error; final NetWorkErrorCallback error;
final ProgressCallback progress; final ProgressCallback progress;
final String host; final String api;
final Map params; final Map params;
ALURL get url => ALURL(host: this.host); final FormData formData;
ALURL get url => ALURL(api: this.api);
///post
Future<void> post() async{ Future<void> post() async{
Response response; ALNetworkTask task = _initNetworkEngin();
Dio dio = new Dio(); task.response = await task.serviceInstance.post(this.url.originUrl, data: this.params);
dio.options.connectTimeout = 5000; //5s _handleNetworkService(task.response);
dio.options.receiveTimeout = 5000;
dio.options.headers = {'user-agent': 'dio', 'common-header': 'xx'};
response = await dio.post(this.url.originUrl, data: this.params);
_handleNetWorkService(response);
} }
/**
* FormData formData = new FormData.from({
"name": "simon",
"age": 25,
});
*/
Future<void> postFormData() async{
ALNetworkTask task = _initNetworkEngin();
task.response = await task.serviceInstance.post(this.url.originUrl, data: this.formData);
_handleNetworkService(task.response);
}
///get
Future<void> excuteGet() async{ Future<void> excuteGet() async{
ALNetworkTask task = _initNetworkEngin();
task.response = await task.serviceInstance.get(this.url.originUrl, queryParameters: ALNetworkHeader().params);
_handleNetworkService(task.response);
}
/**
* FormData formData = new FormData.from({
"name": "wendux",
"age": 25,
"file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
// upload with bytes (List<int>)
"file2": new UploadFileInfo.fromBytes(
utf8.encode("hello world"), "word.txt"),
// Pass multiple files within an Array
"files": [
new UploadFileInfo(new File("./example/upload.txt"), "upload.txt"),
new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
]
});
*/
Future<void> upload() async{
ALNetworkTask task = _initNetworkEngin();
task.response = await task.serviceInstance.post(this.url.originUrl, data: this.formData,onSendProgress: this.progress);
_handleNetworkService(task.response);
}
///download
Future<void> download(String filePath) async{
ALNetworkTask task = _initNetworkEngin();
task.response = await task.serviceInstance.download(this.url.originUrl, filePath, onReceiveProgress: this.progress);
_handleNetworkService(task.response);
}
ALNetworkTask _initNetworkEngin(){
Response response; Response response;
Dio dio = new Dio(); Dio dio = new Dio();
dio.options.headers = ALNetWorkHeader().header; dio.options = ALNetworkHeader().options;
response = await dio.get(this.url.originUrl, queryParameters: ALNetWorkHeader().params); ALNetworkTask task = ALNetworkTask(
_handleNetWorkService(response); serviceInstance:dio,
response: response,
networkContext: this
);
//handle task
taskMap[this.api] = task;
return task;
} }
void _handleNetWorkService(Response response) { void _handleNetworkService(Response response) {
var data = jsonDecode(response.toString()); var data = jsonDecode(response.toString());
if(response.statusCode == 200){ if(data.runtimeType ==Map && response.statusCode == 200){
this.success(NetWorkSuccess(data: data)); if (data['error'] == 0){
this.success(NetworkSuccess(data: data));
}else{
this.error(NetworkError(error: data));
}
}else{ }else{
this.error(NetWorkError(error: data)); this.error(NetworkError(error: data));
} }
} //remove task
taskMap.remove(this.api);
void upload(args) {
}
void download(args) {
} }
} }
\ No newline at end of file
...@@ -27,7 +27,7 @@ class _NetWorkTestPageState extends State<NetWorkTestPage> { ...@@ -27,7 +27,7 @@ class _NetWorkTestPageState extends State<NetWorkTestPage> {
children: <Widget>[ children: <Widget>[
FlatButton( FlatButton(
child: Text('newtWorkTest'), child: Text('newtWorkTest'),
color: Colors.purpleAccent, color: Colors.greenAccent,
onPressed: _netWork, onPressed: _netWork,
), ),
Container( Container(
...@@ -47,20 +47,20 @@ class _NetWorkTestPageState extends State<NetWorkTestPage> { ...@@ -47,20 +47,20 @@ class _NetWorkTestPageState extends State<NetWorkTestPage> {
} }
void _netWork() { void _netWork() {
ALNetWork( ALNetwork(
success: (NetWorkSuccess success){ success: (NetworkSuccess success){
print(success.data); print(success.data);
setState(() { setState(() {
_string = success.data.toString(); _string = success.data.toString();
}); });
}, },
error: (NetWorkError error){ error: (NetworkError error){
print(error.error); print(error.error);
setState(() { setState(() {
_string = error.error.toString(); _string = error.error.toString();
}); });
}, },
host: '/api/v1/index' api: '/api/v1/index'
) )
..excuteGet(); ..excuteGet();
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment