dio
使用:
HttpRequest.request("https://httpbin.org/post",
method: 'post', params: {"name": "Joho"}).then((value) {
print(value);
});
封装 dio -> http_request.dart
import 'package:dio/dio.dart';
import 'http_config.dart';
class HttpRequest {
static final BaseOptions baseOptions = BaseOptions(
baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.timeout);
static final dio = Dio(baseOptions);
static Future request(String url,
{String method = "get",
Map<String, dynamic> params,
interceptor: InterceptorsWrapper}) async {
final options = Options(method: method);
Interceptor defaultInter = InterceptorsWrapper(
onRequest: (RequestOptions request, RequestInterceptorHandler handler) {
print("拦截request");
return request;
}, onResponse: (Response response, ResponseInterceptorHandler handler) {
print("拦截response");
return response;
}, onError: (DioError error, ErrorInterceptorHandler handler) {
print("拦截error");
return error;
});
List<Interceptor> inters = [defaultInter];
if (interceptor != null) {
dio.interceptors.add(interceptor);
}
dio.interceptors.addAll(inters);
try {
Response response = await dio.request(
url,
queryParameters: params,
options: options,
);
return response.data;
} on DioError catch (err) {
return Future.error(err);
}
}
}
http_config.dart
class HttpConfig {
static const baseUrl = "https://httpbin.org";
static const timeout = 5000;
}