Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
G
gmd_flutter
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
mobile
gmd_flutter
Commits
9181a728
Commit
9181a728
authored
May 17, 2019
by
Q14
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
封装网络库请求
parent
b0695e84
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
604 additions
and
256 deletions
+604
-256
HomePage.dart
lib/Home/HomePage.dart
+36
-9
ALNetWork.dart
lib/netWork/ALNetWork.dart
+193
-193
DioUtil.dart
lib/netWork/DioUtil.dart
+372
-51
pubspec.lock
pubspec.lock
+3
-3
No files found.
lib/Home/HomePage.dart
View file @
9181a728
import
'package:flutter/material.dart'
;
import
'package:flutter/material.dart'
;
import
'../netWork/DioUtil.dart'
;
// import '../netWork/DioUtil.dart';
// import 'package:dio/dio.dart';
// import 'dart:async';
class
HomePage
extends
StatefulWidget
{
class
HomePage
extends
StatefulWidget
{
@override
@override
...
@@ -6,15 +10,38 @@ class HomePage extends StatefulWidget {
...
@@ -6,15 +10,38 @@ class HomePage extends StatefulWidget {
}
}
class
_HomePageState
extends
State
<
HomePage
>
{
class
_HomePageState
extends
State
<
HomePage
>
{
void
_incrementCounter
()
{
void
_incrementCounter
()
async
{
setState
(()
{
// print('Come------');
// This call to setState tells the Flutter framework that
// // print('objectaaa');
// something has changed in this State, which causes it to rerun
// DioUtil().get('/api/v1/suggestion',
// the build method below so that the display can reflect the
// data: {
// updated values. If we changed _counter without calling
// 'content': 'aaa',
// setState(), then the build method would not be called again,
// // 'phone': '18601965003'
// and so nothing would appear to happen.
// },
});
// errorCallback: (statusCode) {
// print('NNNNNNNN');
// print('Http error code : $statusCode');
// }
// ).then((data) {
// print('AAAAAAAA');
// print('Http response: $data');
// });
// try {
// Response response = await Dio().post("https://earth.iyanzhi.com/api/v1/suggestion", queryParameters: {'content': 'aaa','phone': '18601965003'
// });
// print(response);
// } catch (e) {
// print(e);
// }
// FormData formData = new FormData.from({
// "username": "username",
// "password": "password",
// });
DioUtil
().
requestR
(
Method
.
post
,
"/api/v1/suggestion"
,
data:
{
"content"
:
"add"
,
"phone"
:
"aaa"
});
}
@override
@override
...
...
lib/netWork/ALNetWork.dart
View file @
9181a728
import
'package:dio/dio.dart'
;
//
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) {
return
data
;
//
return data;
}
else
return
null
;
//
}else return null;
}
//
}
}
//
}
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) {
return
error
[
'errorCode'
];
//
return error['errorCode'];
}
else
return
null
;
//
}else return null;
}
//
}
}
//
}
class
ALURL
{
//
class ALURL {
ALURL
({
this
.
api
})
:
assert
(
api
!=
null
);
//
ALURL({this.api}) : assert(api != null);
final
String
api
;
//
final String api;
static
final
baseUrl
=
'https://earth.iyanzhi.com'
;
//
static final baseUrl = 'https://earth.iyanzhi.com';
String
get
originUrl
=>
(
baseUrl
+
api
);
//
String get originUrl => (baseUrl + api);
}
//
}
class
ALNetworkHeader
{
//
class ALNetworkHeader {
BaseOptions
get
options
{
//
BaseOptions get options{
BaseOptions
option
=
BaseOptions
();
//
BaseOptions option = BaseOptions();
option
.
headers
=
this
.
header
;
//
option.headers =this.header;
return
option
;
//
return option;
}
//
}
Map
<
String
,
dynamic
>
get
header
{
//
Map<String, dynamic> get header{
return
{
//
return {
'Host'
:
'earth.igengmei.com'
,
//
'Host': 'earth.igengmei.com',
'Accept'
:
'*/*'
,
//
'Accept': '*/*',
'Cookie'
:
'_gm_token=fb20fe1550833249; sessionid=qntnckxv4n4nzrl49jmaesc5ylru92yt; _gtid=ae355f92310911e9905700163e0a7a995288'
,
//
'Cookie': '_gm_token=fb20fe1550833249; sessionid=qntnckxv4n4nzrl49jmaesc5ylru92yt; _gtid=ae355f92310911e9905700163e0a7a995288',
'User-Agent'
:
'GMAlpha/1.3.0 (iPhone; iOS 12.1.2; Scale/2.00)'
,
//
'User-Agent': 'GMAlpha/1.3.0 (iPhone; iOS 12.1.2; Scale/2.00)',
'Accept-Language'
:
'en-CN;q=1, zh-Hans-CN;q=0.9'
,
//
'Accept-Language': 'en-CN;q=1, zh-Hans-CN;q=0.9',
'Accept-Encoding'
:
'gzip, deflate'
,
//
'Accept-Encoding': 'gzip, deflate',
'Connection'
:
'keep-alive'
//
'Connection': 'keep-alive'
};
//
};
}
//
}
Map
<
String
,
dynamic
>
get
params
{
//
Map<String, dynamic> get params {
return
{
//
return {
'platform'
:
'iPhone'
,
//
'platform': 'iPhone',
'os_version'
:
'12.1.2'
,
//
'os_version':'12.1.2',
'version'
:
'1.3.0'
,
//
'version':'1.3.0',
'model'
:
'iPhone%206s'
,
//
'model':'iPhone%206s',
'release'
:
'0'
,
//
'release':'0',
'idfa'
:
'119A3567-6C81-40EA-A3ED-A63F7DCAD86B'
,
//
'idfa':'119A3567-6C81-40EA-A3ED-A63F7DCAD86B',
'idfv'
:
'78BE2D94-7252-4C18-A816-2CEE6350B076'
,
//
'idfv':'78BE2D94-7252-4C18-A816-2CEE6350B076',
'device_id'
:
'119A3567-6C81-40EA-A3ED-A63F7DCAD86B'
,
//
'device_id':'119A3567-6C81-40EA-A3ED-A63F7DCAD86B',
'channel'
:
'App%20Store'
,
//
'channel':'App%20Store',
'app_name'
:
'gengmeiios'
,
//
'app_name':'gengmeiios',
'current_city_id'
:
'worldwide'
,
//
'current_city_id':'worldwide',
'lat'
:
'0'
,
//
'lat':'0',
'lng'
:
'0'
,
//
'lng':'0',
'is_WiFi'
:
'(null)'
,
//
'is_WiFi':'(null)',
'phone_id'
:
'iPhone8'
//
'phone_id':'iPhone8'
};
//
};
}
//
}
}
//
}
// 管理任务
//
//
管理任务
class
ALNetworkTask
{
//
class ALNetworkTask {
ALNetworkTask
({
this
.
serviceInstance
,
this
.
networkContext
,
this
.
response
});
//
ALNetworkTask({this.serviceInstance,this.networkContext, this.response});
final
Dio
serviceInstance
;
//
final Dio serviceInstance;
final
ALNetwork
networkContext
;
//
final ALNetwork networkContext;
Response
response
;
//
Response response;
void
cancle
(
String
api
)
{
//
void cancle(String api) {
// CancelToken
//
// 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 {
/**
//
/**
* 任务映射表
//
* 任务映射表
* 外部可以通过 ALNetwork.taskMap 获取
//
* 外部可以通过 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
.
api
,
//
this.api,
this
.
params
,
//
this.params,
this
.
formData
})
:
assert
(
api
!=
null
);
//
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
api
;
//
final String api;
final
Map
params
;
//
final Map params;
final
FormData
formData
;
//
final FormData formData;
ALURL
get
url
=>
ALURL
(
api:
this
.
api
);
//
ALURL get url => ALURL(api: this.api);
///post
//
///post
Future
<
void
>
post
()
async
{
//
Future<void> post() async{
ALNetworkTask
task
=
_initNetworkEngin
();
//
ALNetworkTask task = _initNetworkEngin();
task
.
response
=
await
task
.
serviceInstance
.
post
(
this
.
url
.
originUrl
,
data:
this
.
params
);
//
task.response = await task.serviceInstance.post(this.url.originUrl, data: this.params);
_handleNetworkService
(
task
.
response
);
//
_handleNetworkService(task.response);
}
//
}
/**
//
/**
* FormData formData = new FormData.from({
//
* FormData formData = new FormData.from({
"name": "simon",
//
"name": "simon",
"age": 25,
//
"age": 25,
});
//
});
*/
//
*/
Future
<
void
>
postFormData
()
async
{
//
Future<void> postFormData() async{
ALNetworkTask
task
=
_initNetworkEngin
();
//
ALNetworkTask task = _initNetworkEngin();
task
.
response
=
await
task
.
serviceInstance
.
post
(
this
.
url
.
originUrl
,
data:
this
.
formData
);
//
task.response = await task.serviceInstance.post(this.url.originUrl, data: this.formData);
_handleNetworkService
(
task
.
response
);
//
_handleNetworkService(task.response);
}
//
}
///get
//
///get
Future
<
void
>
excuteGet
()
async
{
//
Future<void> excuteGet() async{
ALNetworkTask
task
=
_initNetworkEngin
();
//
ALNetworkTask task = _initNetworkEngin();
task
.
response
=
await
task
.
serviceInstance
.
get
(
this
.
url
.
originUrl
,
queryParameters:
ALNetworkHeader
().
params
);
//
task.response = await task.serviceInstance.get(this.url.originUrl, queryParameters: ALNetworkHeader().params);
_handleNetworkService
(
task
.
response
);
//
_handleNetworkService(task.response);
}
//
}
/**
// /**
* FormData formData = new FormData.from({
// * FormData formData = new FormData.from({
"name": "wendux",
// "name": "wendux",
"age": 25,
// "age": 25,
"file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
// "file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
// upload with bytes (List<int>)
// // upload with bytes (List<int>)
"file2": new UploadFileInfo.fromBytes(
// "file2": new UploadFileInfo.fromBytes(
utf8.encode("hello world"), "word.txt"),
// utf8.encode("hello world"), "word.txt"),
// Pass multiple files within an Array
// // Pass multiple files within an Array
"files": [
// "files": [
new UploadFileInfo(new File("./example/upload.txt"), "upload.txt"),
// new UploadFileInfo(new File("./example/upload.txt"), "upload.txt"),
new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
// new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
]
// ]
});
// });
*/
// */
Future
<
void
>
upload
()
async
{
// Future<void> upload() async{
ALNetworkTask
task
=
_initNetworkEngin
();
// ALNetworkTask task = _initNetworkEngin();
task
.
response
=
await
task
.
serviceInstance
.
post
(
this
.
url
.
originUrl
,
data:
this
.
formData
,
onSendProgress:
this
.
progress
);
// task.response = await task.serviceInstance.post(this.url.originUrl, data: this.formData,onSendProgress: this.progress);
_handleNetworkService
(
task
.
response
);
// _handleNetworkService(task.response);
}
// }
///download
// ///download
Future
<
void
>
download
(
String
filePath
)
async
{
// Future<void> download(String filePath) async{
ALNetworkTask
task
=
_initNetworkEngin
();
// ALNetworkTask task = _initNetworkEngin();
task
.
response
=
await
task
.
serviceInstance
.
download
(
this
.
url
.
originUrl
,
filePath
,
onReceiveProgress:
this
.
progress
);
// task.response = await task.serviceInstance.download(this.url.originUrl, filePath, onReceiveProgress: this.progress);
_handleNetworkService
(
task
.
response
);
// _handleNetworkService(task.response);
}
// }
ALNetworkTask
_initNetworkEngin
(){
// ALNetworkTask _initNetworkEngin(){
Response
response
;
// Response response;
Dio
dio
=
new
Dio
();
// Dio dio = new Dio();
dio
.
options
=
ALNetworkHeader
().
options
;
// dio.options = ALNetworkHeader().options;
ALNetworkTask
task
=
ALNetworkTask
(
// ALNetworkTask task = ALNetworkTask(
serviceInstance:
dio
,
// serviceInstance:dio,
response:
response
,
// response: response,
networkContext:
this
// networkContext: this
);
// );
//handle task
// //handle task
taskMap
[
this
.
api
]
=
task
;
// taskMap[this.api] = task;
return
task
;
// return task;
}
// }
void
_handleNetworkService
(
Response
response
)
{
// void _handleNetworkService(Response response) {
var
data
=
jsonDecode
(
response
.
toString
());
// var data = jsonDecode(response.toString());
if
(
data
.
runtimeType
==
Map
&&
response
.
statusCode
==
200
){
// if(data.runtimeType ==Map && response.statusCode == 200){
if
(
data
[
'error'
]
==
0
){
// if (data['error'] == 0){
this
.
success
(
NetworkSuccess
(
data:
data
));
// this.success(NetworkSuccess(data: data));
}
else
{
// }else{
this
.
error
(
NetworkError
(
error:
data
));
// this.error(NetworkError(error: data));
}
// }
}
else
{
// }else{
this
.
error
(
NetworkError
(
error:
data
));
// this.error(NetworkError(error: data));
}
// }
//remove task
// //remove task
taskMap
.
remove
(
this
.
api
);
// taskMap.remove(this.api);
}
// }
}
// }
\ No newline at end of file
\ No newline at end of file
lib/netWork/DioUtil.dart
View file @
9181a728
...
@@ -3,6 +3,59 @@ import 'dart:io';
...
@@ -3,6 +3,59 @@ import 'dart:io';
import
'package:dio/dio.dart'
;
import
'package:dio/dio.dart'
;
/**
* @Author: thl
* @GitHub: https://github.com/Sky24n
* @JianShu: https://www.jianshu.com/u/cbf2ad25d33a
* @Email: 863764940@qq.com
* @Description: Dio Util.
* @Date: 2018/12/19
*/
/// <BaseResp<T> 返回 status code msg data.
class
BaseResp
<
T
>
{
String
status
;
int
code
;
String
msg
;
T
data
;
BaseResp
(
this
.
status
,
this
.
code
,
this
.
msg
,
this
.
data
);
@override
String
toString
()
{
StringBuffer
sb
=
new
StringBuffer
(
'{'
);
sb
.
write
(
"
\"
status
\"
:
\"
$status
\"
"
);
sb
.
write
(
",
\"
code
\"
:
$code
"
);
sb
.
write
(
",
\"
msg
\"
:
\"
$msg
\"
"
);
sb
.
write
(
",
\"
data
\"
:
\"
$data
\"
"
);
sb
.
write
(
'}'
);
return
sb
.
toString
();
}
}
/// <BaseRespR<T> 返回 status code msg data Response.
class
BaseRespR
<
T
>
{
String
status
;
int
code
;
String
msg
;
T
data
;
Response
response
;
BaseRespR
(
this
.
status
,
this
.
code
,
this
.
msg
,
this
.
data
,
this
.
response
);
@override
String
toString
()
{
StringBuffer
sb
=
new
StringBuffer
(
'{'
);
sb
.
write
(
"
\"
status
\"
:
\"
$status
\"
"
);
sb
.
write
(
",
\"
code
\"
:
$code
"
);
sb
.
write
(
",
\"
msg
\"
:
\"
$msg
\"
"
);
sb
.
write
(
",
\"
data
\"
:
\"
$data
\"
"
);
sb
.
write
(
'}'
);
return
sb
.
toString
();
}
}
/// 请求方法.
class
Method
{
class
Method
{
static
final
String
get
=
"GET"
;
static
final
String
get
=
"GET"
;
static
final
String
post
=
"POST"
;
static
final
String
post
=
"POST"
;
...
@@ -12,88 +65,357 @@ class Method {
...
@@ -12,88 +65,357 @@ class Method {
static
final
String
patch
=
"PATCH"
;
static
final
String
patch
=
"PATCH"
;
}
}
///Http配置.
class
HttpConfig
{
/// constructor.
HttpConfig
({
this
.
status
,
this
.
code
,
this
.
msg
,
this
.
data
,
this
.
options
,
this
.
pem
,
this
.
pKCSPath
,
this
.
pKCSPwd
,
});
/// BaseResp [String status]字段 key, 默认:status.
String
status
;
/// BaseResp [int code]字段 key, 默认:errorCode.
String
code
;
/// BaseResp [String msg]字段 key, 默认:errorMsg.
String
msg
;
/// BaseResp [T data]字段 key, 默认:data.
String
data
;
/// Options.
BaseOptions
options
;
/// 详细使用请查看dio官网 https://github.com/flutterchina/dio/blob/flutter/README-ZH.md#Https证书校验.
/// PEM证书内容.
String
pem
;
/// 详细使用请查看dio官网 https://github.com/flutterchina/dio/blob/flutter/README-ZH.md#Https证书校验.
/// PKCS12 证书路径.
String
pKCSPath
;
/// 详细使用请查看dio官网 https://github.com/flutterchina/dio/blob/flutter/README-ZH.md#Https证书校验.
/// PKCS12 证书密码.
String
pKCSPwd
;
}
/// 单例 DioUtil.
/// debug模式下可以打印请求日志. DioUtil.openDebug().
/// dio详细使用请查看dio官网(https://github.com/flutterchina/dio).
class
DioUtil
{
class
DioUtil
{
static
final
DioUtil
_instance
=
DioUtil
.
_init
();
static
final
DioUtil
_instance
=
DioUtil
.
_init
();
static
Dio
_dio
;
static
Dio
_dio
;
/// BaseResp [String status]字段 key, 默认:status.
String
_statusKey
=
"status"
;
/// BaseResp [int code]字段 key, 默认:errorCode.
String
_codeKey
=
"errorCode"
;
/// BaseResp [String msg]字段 key, 默认:errorMsg.
String
_msgKey
=
"errorMsg"
;
/// BaseResp [T data]字段 key, 默认:data.
String
_dataKey
=
"data"
;
/// Options.
static
BaseOptions
_options
=
getDefOptions
();
static
BaseOptions
_options
=
getDefOptions
();
/// PEM证书内容.
String
_pem
;
/// PKCS12 证书路径.
String
_pKCSPath
;
/// PKCS12 证书密码.
String
_pKCSPwd
;
/// 是否是debug模式.
static
bool
_isDebug
=
false
;
static
DioUtil
getInstance
()
{
return
_instance
;
}
factory
DioUtil
()
{
factory
DioUtil
()
{
return
_instance
;
return
_instance
;
}
}
DioUtil
.
_init
()
{
DioUtil
.
_init
()
{
_dio
=
new
Dio
();
_dio
=
new
Dio
(
_options
);
}
}
static
BaseOptions
getDefOptions
()
{
/// 打开debug模式.
BaseOptions
options
=
BaseOptions
();
static
void
openDebug
()
{
options
.
connectTimeout
=
10
*
1000
;
_isDebug
=
true
;
options
.
receiveTimeout
=
20
*
1000
;
}
options
.
contentType
=
ContentType
.
parse
(
'application/x-www-form-urlencoded'
);
Map
<
String
,
dynamic
>
headers
=
Map
<
String
,
dynamic
>();
/// set Config.
headers
[
'Accept'
]
=
'application/json'
;
void
setConfig
(
HttpConfig
config
)
{
_statusKey
=
config
.
status
??
_statusKey
;
_codeKey
=
config
.
code
??
_codeKey
;
_msgKey
=
config
.
msg
??
_msgKey
;
_dataKey
=
config
.
data
??
_dataKey
;
_mergeOption
(
config
.
options
);
_pem
=
config
.
pem
??
_pem
;
if
(
_dio
!=
null
)
{
_dio
.
options
=
_options
;
if
(
_pem
!=
null
)
{
// httpClientAdapter
(
_dio
.
httpClientAdapter
as
DefaultHttpClientAdapter
).
onHttpClientCreate
=
(
client
)
{
client
.
badCertificateCallback
=
(
X509Certificate
cert
,
String
host
,
int
port
)
{
if
(
cert
.
pem
==
_pem
)
{
// 证书一致,则放行
return
true
;
}
return
false
;
};
};
String
platform
;
}
if
(
Platform
.
isAndroid
)
{
if
(
_pKCSPath
!=
null
)
{
platform
=
"Android"
;
(
_dio
.
httpClientAdapter
as
DefaultHttpClientAdapter
).
onHttpClientCreate
=
(
client
)
{
}
else
if
(
Platform
.
isIOS
)
{
SecurityContext
sc
=
new
SecurityContext
();
platform
=
"IOS"
;
//file为证书路径
sc
.
setTrustedCertificates
(
_pKCSPath
,
password:
_pKCSPwd
);
HttpClient
httpClient
=
new
HttpClient
(
context:
sc
);
return
httpClient
;
};
}
}
}
headers
[
'OS'
]
=
platform
;
}
options
.
headers
=
headers
;
return
options
;
/// Make http request with options.
/// [method] The request method.
/// [path] The url path.
/// [data] The request data
/// [options] The request options.
/// <BaseResp<T> 返回 status code msg data .
Future
<
BaseResp
<
T
>>
request
<
T
>(
String
method
,
String
path
,
{
data
,
Options
options
,
CancelToken
cancelToken
})
async
{
Response
response
=
await
_dio
.
request
(
path
,
data:
data
,
options:
_checkOptions
(
method
,
options
),
cancelToken:
cancelToken
);
_printHttpLog
(
response
);
String
_status
;
int
_code
;
String
_msg
;
T
_data
;
if
(
response
.
statusCode
==
HttpStatus
.
ok
||
response
.
statusCode
==
HttpStatus
.
created
)
{
try
{
if
(
response
.
data
is
Map
)
{
_status
=
(
response
.
data
[
_statusKey
]
is
int
)
?
response
.
data
[
_statusKey
].
toString
()
:
response
.
data
[
_statusKey
];
_code
=
(
response
.
data
[
_codeKey
]
is
String
)
?
int
.
tryParse
(
response
.
data
[
_codeKey
])
:
response
.
data
[
_codeKey
];
_msg
=
response
.
data
[
_msgKey
];
_data
=
response
.
data
[
_dataKey
];
}
else
{
Map
<
String
,
dynamic
>
_dataMap
=
_decodeData
(
response
);
_status
=
(
_dataMap
[
_statusKey
]
is
int
)
?
_dataMap
[
_statusKey
].
toString
()
:
_dataMap
[
_statusKey
];
_code
=
(
_dataMap
[
_codeKey
]
is
String
)
?
int
.
tryParse
(
_dataMap
[
_codeKey
])
:
_dataMap
[
_codeKey
];
_msg
=
_dataMap
[
_msgKey
];
_data
=
_dataMap
[
_dataKey
];
}
return
new
BaseResp
(
_status
,
_code
,
_msg
,
_data
);
}
catch
(
e
)
{
return
new
Future
.
error
(
new
DioError
(
response:
response
,
message:
"data parsing exception..."
,
type:
DioErrorType
.
RESPONSE
,
));
}
}
return
new
Future
.
error
(
new
DioError
(
response:
response
,
message:
"statusCode:
$response
.statusCode, service error"
,
type:
DioErrorType
.
RESPONSE
,
));
}
}
setOptions
(
BaseOptions
options
)
{
/// Make http request with options.
_options
=
options
;
/// [method] The request method.
_dio
.
options
=
_options
;
/// [path] The url path.
/// [data] The request data
/// [options] The request options.
/// <BaseRespR<T> 返回 status code msg data Response.
Future
<
BaseRespR
<
T
>>
requestR
<
T
>(
String
method
,
String
path
,
{
data
,
Options
options
,
CancelToken
cancelToken
})
async
{
Response
response
=
await
_dio
.
request
(
path
,
data:
data
,
options:
_checkOptions
(
method
,
options
),
cancelToken:
cancelToken
);
_printHttpLog
(
response
);
String
_status
;
int
_code
;
String
_msg
;
T
_data
;
if
(
response
.
statusCode
==
HttpStatus
.
ok
||
response
.
statusCode
==
HttpStatus
.
created
)
{
try
{
if
(
response
.
data
is
Map
)
{
_status
=
(
response
.
data
[
_statusKey
]
is
int
)
?
response
.
data
[
_statusKey
].
toString
()
:
response
.
data
[
_statusKey
];
_code
=
(
response
.
data
[
_codeKey
]
is
String
)
?
int
.
tryParse
(
response
.
data
[
_codeKey
])
:
response
.
data
[
_codeKey
];
_msg
=
response
.
data
[
_msgKey
];
_data
=
response
.
data
[
_dataKey
];
}
else
{
Map
<
String
,
dynamic
>
_dataMap
=
_decodeData
(
response
);
_status
=
(
_dataMap
[
_statusKey
]
is
int
)
?
_dataMap
[
_statusKey
].
toString
()
:
_dataMap
[
_statusKey
];
_code
=
(
_dataMap
[
_codeKey
]
is
String
)
?
int
.
tryParse
(
_dataMap
[
_codeKey
])
:
_dataMap
[
_codeKey
];
_msg
=
_dataMap
[
_msgKey
];
_data
=
_dataMap
[
_dataKey
];
}
return
new
BaseRespR
(
_status
,
_code
,
_msg
,
_data
,
response
);
}
catch
(
e
)
{
return
new
Future
.
error
(
new
DioError
(
response:
response
,
message:
"data parsing exception..."
,
type:
DioErrorType
.
RESPONSE
,
));
}
}
return
new
Future
.
error
(
new
DioError
(
response:
response
,
message:
"statusCode:
$response
.statusCode, service error"
,
type:
DioErrorType
.
RESPONSE
,
));
}
}
Future
<
Map
<
String
,
dynamic
>>
get
(
String
path
,
{
pathParams
,
data
,
Function
errorCallback
})
{
/// Download the file and save it in local. The default http method is "GET",you can custom it by [Options.method].
return
request
(
path
,
method:
Method
.
get
,
pathParams:
pathParams
,
data:
data
,
errorCallback:
errorCallback
);
/// [urlPath]: The file url.
/// [savePath]: The path to save the downloading file later.
/// [onProgress]: The callback to listen downloading progress.please refer to [OnDownloadProgress].
Future
<
Response
>
download
(
String
urlPath
,
savePath
,
{
CancelToken
cancelToken
,
data
,
Options
options
,
})
{
return
_dio
.
download
(
urlPath
,
savePath
,
cancelToken:
cancelToken
,
data:
data
,
options:
options
);
}
}
Future
<
Map
<
String
,
dynamic
>>
post
(
String
path
,
{
pathParams
,
data
,
Function
errorCallback
})
{
/// decode response data.
return
request
(
path
,
method:
Method
.
post
,
pathParams:
pathParams
,
data:
data
,
errorCallback:
errorCallback
);
Map
<
String
,
dynamic
>
_decodeData
(
Response
response
)
{
if
(
response
==
null
||
response
.
data
==
null
||
response
.
data
.
toString
().
isEmpty
)
{
return
new
Map
();
}
return
json
.
decode
(
response
.
data
.
toString
());
}
}
Future
<
Map
<
String
,
dynamic
>>
request
(
String
path
,{
String
method
,
Map
pathParams
,
data
,
Function
errorCallback
})
async
{
/// check Options.
///restful请求处理
Options
_checkOptions
(
method
,
options
)
{
if
(
pathParams
!=
null
)
{
print
(
'_checkOptionsAAAA'
);
pathParams
.
forEach
((
key
,
value
)
{
print
(
options
);
if
(
path
.
indexOf
(
key
)
!=
-
1
)
{
if
(
options
==
null
)
{
path
=
path
.
replaceAll
(
":
$key
"
,
value
.
toString
());
options
=
new
Options
();
}
});
}
}
options
.
method
=
method
;
return
options
;
}
/// merge Option.
void
_mergeOption
(
BaseOptions
opt
)
{
_options
.
method
=
opt
.
method
??
_options
.
method
;
_options
.
headers
=
(
new
Map
.
from
(
_options
.
headers
))..
addAll
(
opt
.
headers
);
_options
.
baseUrl
=
opt
.
baseUrl
??
_options
.
baseUrl
;
_options
.
connectTimeout
=
opt
.
connectTimeout
??
_options
.
connectTimeout
;
_options
.
receiveTimeout
=
opt
.
receiveTimeout
??
_options
.
receiveTimeout
;
_options
.
responseType
=
opt
.
responseType
??
_options
.
responseType
;
_options
.
extra
=
(
new
Map
.
from
(
_options
.
extra
))..
addAll
(
opt
.
extra
);
_options
.
contentType
=
opt
.
contentType
??
_options
.
contentType
;
_options
.
validateStatus
=
opt
.
validateStatus
??
_options
.
validateStatus
;
_options
.
followRedirects
=
opt
.
followRedirects
??
_options
.
followRedirects
;
}
Response
response
=
await
_dio
.
request
(
path
,
data:
data
,
options:
Options
(
method:
method
));
/// print Http Log.
void
_printHttpLog
(
Response
response
)
{
if
(!
_isDebug
)
{
return
;
}
try
{
print
(
"----------------Http Log----------------"
+
"
\n
[statusCode]: "
+
response
.
statusCode
.
toString
()
+
"
\n
[request ]: "
+
_getOptionsStr
(
response
.
request
));
_printDataStr
(
"reqdata "
,
response
.
request
.
data
);
_printDataStr
(
"response"
,
response
.
data
);
}
catch
(
ex
)
{
print
(
"Http Log"
+
" error......"
);
}
}
if
(
response
.
statusCode
==
HttpStatus
.
ok
||
response
.
statusCode
==
HttpStatus
.
created
)
{
/// get Options Str.
try
{
String
_getOptionsStr
(
Options
request
)
{
if
(
response
.
data
is
Map
)
{
return
"method: "
+
return
response
.
data
;
request
.
method
;
}
else
{
}
return
json
.
decode
(
response
.
data
.
toString
());
}
}
catch
(
e
)
{
return
null
;
/// print Data Str.
void
_printDataStr
(
String
tag
,
Object
value
)
{
String
da
=
value
.
toString
();
while
(
da
.
isNotEmpty
)
{
if
(
da
.
length
>
512
)
{
print
(
"[
$tag
]: "
+
da
.
substring
(
0
,
512
));
da
=
da
.
substring
(
512
,
da
.
length
);
}
else
{
print
(
"[
$tag
]: "
+
da
);
da
=
""
;
}
}
}
else
{
_handleHttpError
(
response
.
statusCode
);
if
(
errorCallback
!=
null
)
{
errorCallback
(
response
.
statusCode
);
}
return
null
;
}
}
}
}
///处理Http错误码
/// get dio.
void
_handleHttpError
(
int
errorCode
)
{
Dio
getDio
()
{
return
_dio
;
}
/// create new dio.
static
Dio
createNewDio
([
Options
options
])
{
Dio
dio
=
new
Dio
();
return
dio
;
}
}
}
/// get Def Options.
\ No newline at end of file
static
BaseOptions
getDefOptions
()
{
BaseOptions
options
=
BaseOptions
();
options
.
connectTimeout
=
10
*
1000
;
options
.
receiveTimeout
=
20
*
1000
;
options
.
contentType
=
ContentType
.
parse
(
'application/x-www-form-urlencoded'
);
options
.
baseUrl
=
'https://earth.iyanzhi.com'
;
Map
<
String
,
dynamic
>
headers
=
Map
<
String
,
dynamic
>();
headers
[
'Accept'
]
=
'application/json'
;
return
options
;
}
}
pubspec.lock
View file @
9181a728
...
@@ -7,7 +7,7 @@ packages:
...
@@ -7,7 +7,7 @@ packages:
name: async
name: async
url: "https://pub.flutter-io.cn"
url: "https://pub.flutter-io.cn"
source: hosted
source: hosted
version: "2.
1
.0"
version: "2.
2
.0"
boolean_selector:
boolean_selector:
dependency: transitive
dependency: transitive
description:
description:
...
@@ -94,7 +94,7 @@ packages:
...
@@ -94,7 +94,7 @@ packages:
name: quiver
name: quiver
url: "https://pub.flutter-io.cn"
url: "https://pub.flutter-io.cn"
source: hosted
source: hosted
version: "2.0.
2
"
version: "2.0.
3
"
sky_engine:
sky_engine:
dependency: transitive
dependency: transitive
description: flutter
description: flutter
...
@@ -141,7 +141,7 @@ packages:
...
@@ -141,7 +141,7 @@ packages:
name: test_api
name: test_api
url: "https://pub.flutter-io.cn"
url: "https://pub.flutter-io.cn"
source: hosted
source: hosted
version: "0.2.
4
"
version: "0.2.
5
"
typed_data:
typed_data:
dependency: transitive
dependency: transitive
description:
description:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment