封装网络请求, 我使用了 Dio 库。
HttpUtil.dart
import 'package:dio/dio.dart';
class HttpUtil {
static HttpUtil instance;
Dio dio;
BaseOptions options;
String baseUrl = "https://5d5a45132257cc001496241b.mockapi.io/api/";
static HttpUtil getInstance() {
print('getInstance');
if (instance == null) {
instance = new HttpUtil();
}
return instance;
}
HttpUtil() {
options = BaseOptions(
// 请求基地址,可以包含子路径,如: "//www.google.com/api/".
baseUrl: baseUrl,
//连接服务器超时时间,单位是毫秒.
connectTimeout: 10000,
/// 响应流上前后两次接受到数据的间隔,单位为毫秒。如果两次间隔超过[receiveTimeout],
/// [Dio] 将会抛出一个[DioErrorType.RECEIVE_TIMEOUT]的异常.
/// 注意: 这并不是接收数据的总时限.
receiveTimeout: 3000,
headers: {},
);
dio = new Dio(options);
}
resolve(List api, {data, options, cancelToken}) async {
switch (api[1]) {
case 'get':
return await this.get(
api[0],
data: data,
options: options,
cancelToken: cancelToken
);
break;
case 'post':
return await this.post(
api[0],
data: data,
options: options,
cancelToken: cancelToken
);
break;
default:
break;
}
}
get(url, {data, options, cancelToken}) async {
print('get请求启动! url:$url ,body: $data');
Response response;
try {
response = await dio.get(
url,
queryParameters: data,
cancelToken: cancelToken,
);
print('get请求成功! response.data:${response.data}');
} on DioError catch (e) {
if (CancelToken.isCancel(e)) {
print('get请求取消! ' + e.message);
}
print('get请求发生错误:$e');
}
return response.data;
}
post(url, {data, options, cancelToken}) async {
print('post请求启动! url:$url ,body: $data');
Response response;
try {
response = await dio.post(
url,
data: data,
cancelToken: cancelToken,
);
print('post请求成功! response.data:${response.data}');
} on DioError catch (e) {
if (CancelToken.isCancel(e)) {
print('post请求取消! ' + e.message);
}
print('post请求发生错误:$e');
}
return response.data;
}
}
Api.dart
class Api {
static List USER_LIST = ['user', 'get'];
}
使用方式:
Future getData() async {
var data = {'pageIndex': 1, 'pageSize': 10};
var response = await HttpUtil().resolve(Api.USER_LIST, data: data);
print(response);
print(response is List); // true
print(response[0] is Map); // true
}
可以看到, 返回的 json 数据自动转化为了 List 或 Map 格式的数据。