GitHub - dio是一个强大的Dart Http请求库

path/param/options(配置headers/timeout/baseurl等)
1
2
3
4
5
6
///await返回一个Response(Future),包含data,headers,request(本次请求信息),statusCode
response = await request(
"/test",
data: {"id": 12, "name": "xx"},
options: Options(method: "GET"),
);

封装成单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import 'dart:io';//http
import 'package:dio/dio.dart';//http
import 'dart:convert';//json
import 'package:crypto/crypto.dart';//MD5
import 'package:convert/convert.dart';//MD5
import 'package:flustars/flustars.dart';//本地储存sputil

//单例网络请求库(封装dio)
class DioUtil {
static final DioUtil _singleton = DioUtil._init();
static Dio _dio;

BaseOptions _options = defaultOptions();

static DioUtil getInstance() {
return _singleton;
}

factory DioUtil() {
return _singleton;
}

DioUtil._init() {
_dio = new Dio(_options);
}

static BaseOptions defaultOptions() {
BaseOptions options = new BaseOptions();
options.contentType = ContentType.parse("application/x-www-form-urlencoded");
options.responseType = ResponseType.json;
options.connectTimeout = 1000 * 10;
options.receiveTimeout = 1000 * 20;
options.queryParameters = {"token":SpUtil.getString("UserToken")};//公共参数
options.headers = {"platform":"ios"};//请求头
return options;
}

Options _checkOptions(method, options) {
if (options == null) {
options = new Options();
}
options.method = method;
return options;
}

//HTTP请求
Future request<T>(String method,
String path,
{data,Options options,CancelToken cancelToken}) async{
Options currentOptions = options;
currentOptions.headers = {"sign":generateMd5(json.encode(data))};//签名..
//关键API
Response response = await _dio.request(path,
data: data,
options: _checkOptions(method, currentOptions),
cancelToken: cancelToken);
if (response.statusCode == HttpStatus.ok || response.statusCode == HttpStatus.created) {
try {
return BaseRespModel.fromJson(_decodeData(response));
} catch (e) {
return new Future.error(
new DioError(
response: response,
message: "data parsing exception...",
type: DioErrorType.RESPONSE
)
);
}
} else {
return new Future.error(
new DioError(
response: response,
message: "statusCode: $response.statusCode, serverError",
type: DioErrorType.RESPONSE
)
);
}
//HTTP下载
Future<Response> download(String urlPath,savePath,
{ProgressCallback onProgress,
CancelToken cancelToken,
data,
Options options}){
return _dio.download(urlPath, savePath,
onReceiveProgress: onProgress,
cancelToken: cancelToken,
data: data,
options: options);
}
}

/// decode response data.
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());
}

// md5 加密
String generateMd5(String data) {
var content = new Utf8Encoder().convert(data);
var digest = md5.convert(content);
// 这里其实就是 digest.toString()
return hex.encode(digest.bytes);
}
}

//统一返回模型
class BaseRespModel<T> {
String status;
int code;
String msg;
T data;

BaseRespModel(this.status, this.code, this.msg, this.data);

BaseRespModel.fromJson(Map<String, dynamic> json)
: status = json['status'],
code = json['code'],
msg = json['msg'],
data = json['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();
}
}

///请求方法枚举
class Method {
static final String get = "GET";
static final String post = "POST";
static final String put = "PUT";
static final String head = "HEAD";
static final String delete = "DELETE";
static final String patch = "PATCH";
}


Dart内置::dart:convert::库,包含简单JSON编码和解码。

  • 解码:Map<String, dynamic> map = json.decode(jsonString);
  • 编码:String jsonString = JSON.encode(model);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class LoginReq {
String username;
String password;

LoginReq(this.username, this.password);

LoginReq.fromJson(Map<String, dynamic> json)
: username = json['username'],
password = json['password'];

Map<String, dynamic> toJson() => {
'username': username,
'password': password,
};

@override
String toString() {
return '{' +
" \"username\":\"" +
username +
"\"" +
", \"password\":\"" +
password +
"\"" +
'}';
}
}

thanks for your reading~