Response response;
var dio =Dio();
response =await dio.get('/test?id=12&name=wendu');
print(response.data.toString());
// Optionally the request above could also be done as
response =await dio.get('/test', queryParameters: {'id':12, 'name':'wendu'});
print(response.data.toString());
var dio =Dio(); // with default Options// Set default configs
dio.options.baseUrl ='https://www.xx.com/api';
dio.options.connectTimeout =5000; //5s
dio.options.receiveTimeout =3000;
// or new Dio with a BaseOptions instance.var options =BaseOptions(
baseUrl:'https://www.xx.com/api',
connectTimeout:5000,
receiveTimeout:3000,
);
Dio dio =Dio(options);
{
/// Http method.String method;
/// Request base url, it can contain sub path, like: 'https://www.google.com/api/'.String baseUrl;
/// Http request headers.Map<String, dynamic> headers;
/// Timeout in milliseconds for opening url.int connectTimeout;
/// Whenever more than [receiveTimeout] (in milliseconds) passes between two events from response stream, /// [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT]. /// Note: This is not the receiving time limitation.int receiveTimeout;
/// Request data, can be any type.T data;
/// If the `path` starts with 'http(s)', the `baseURL` will be ignored, otherwise, /// it will be combined and then resolved with the baseUrl.String path='';
/// The request Content-Type. The default value is 'application/json; charset=utf-8'. /// If you want to encode request body with 'application/x-www-form-urlencoded', /// you can set [Headers.formUrlEncodedContentType], and [Dio] /// will automatically encode the request body.String contentType;
/// [responseType] indicates the type of data that the server will respond with /// options which defined in [ResponseType] are `JSON`, `STREAM`, `PLAIN`. /// /// The default value is `JSON`, dio will parse response string to json object automatically /// when the content-type of response is 'application/json'. /// /// If you want to receive response data with binary bytes, for example, /// downloading a image, use `STREAM`. /// /// If you want to receive the response data with String, use `PLAIN`.ResponseType responseType;
/// `validateStatus` defines whether the request is successful for a given /// HTTP response status code. If `validateStatus` returns `true` , /// the request will be perceived as successful; otherwise, considered as failed.ValidateStatus validateStatus;
/// Custom field that you can retrieve it later in [Interceptor]、[Transformer] and the [Response] object.Map<String, dynamic> extra;
/// Common query parametersMap<String, dynamic/*String|Iterable<String>*/> queryParameters;
/// [collectionFormat] indicates the format of collection data in request /// options which defined in [CollectionFormat] are `csv`, `ssv`, `tsv`, `pipes`, `multi`,`multiCompatible`. /// The default value is `multiCompatible`lateCollectionFormat collectionFormat;
}
{
/// Response body. may have been transformed, please refer to [ResponseType].T? data;
/// Response headers.Headers headers;
/// The corresponding request info.RequestOptions requestOptions;
/// Http status code.int? statusCode;
String? statusMessage;
/// Whether redirect bool? isRedirect;
/// redirect info List<RedirectInfo> redirects ;
/// Returns the final real request uri (maybe redirect). Uri realUri;
/// Custom field that you can retrieve it later in `then`.Map<String, dynamic> extra;
}
对于每个 dio 实例,我们可以添加一个或多个拦截器,通过它们,我们可以在请求/响应/错误被 then 或 catchError 处理之前拦截它们。
dio.interceptors.add(InterceptorsWrapper(
onRequest:(options, handler){
// Do something before request is sentreturn handler.next(options); //continue// If you want to resolve the request with some custom data,// you can resolve a `Response` object eg: `handler.resolve(response)`.// If you want to reject the request with a error message,// you can reject a `DioError` object eg: `handler.reject(dioError)`
},
onResponse:(response,handler) {
// Do something with response datareturn handler.next(response); // continue// If you want to reject the request with a error message,// you can reject a `DioError` object eg: `handler.reject(dioError)`
},
onError: (DioError e, handler) {
// Do something with response errorreturn handler.next(e);//continue// If you want to resolve the request with some custom data,// you can resolve a `Response` object eg: `handler.resolve(response)`.
}
));
tokenDio =Dio(); //Create a new instance to request the token.
tokenDio.options = dio.options.copyWith();
dio.interceptors.add(InterceptorsWrapper(
onRequest:(Options options, handler){
// If no token, request token firstly and lock this interceptor// to prevent other request enter this interceptor.
dio.interceptors.requestLock.lock();
// We use a new Dio(to avoid dead lock) instance to request token.
tokenDio.get('/token').then((response){
//Set the token to headers
options.headers['token'] = response.data['data']['token'];
handler.next(options); //continue
}).catchError((error, stackTrace) {
handler.reject(error, true);
}).whenComplete(() => dio.interceptors.requestLock.unlock());
}
));
您可以通过调用 clear() 来清除等待队列;
别名
当 **请求** 拦截器被锁定后,传入的请求将会暂停,这相当于我们锁定了当前的 dio 实例,因此,Dio 为 **请求** 拦截器的 lock/unlock 提供了两个别名。
try {
//404await dio.get('https://wendux.github.io/xsddddd');
} onDioErrorcatch (e) {
// The request was made and the server responded with a status code// that falls out of the range of 2xx and is also not 304.if (e.response) {
print(e.response.data)
print(e.response.headers)
print(e.response.requestOptions)
} else {
// Something happened in setting up or sending the request that triggered an Errorprint(e.requestOptions)
print(e.message)
}
}
DioError 结构
{
/// Response info, it may be `null` if the request can't reach to /// the http server, for example, occurring a dns error, network is not available.Response? response;
/// Request info.RequestOptions? requestOptions;
/// Error descriptions.String message;
DioErrorType type;
/// The original error/exception object; It's usually not null when `type` /// is DioErrorType.DEFAULTdynamic? error;
}
DioErrorType
enumDioErrorType {
/// It occurs when url is opened timeout.
connectTimeout,
/// It occurs when url is sent timeout.
sendTimeout,
///It occurs when receiving timeout.
receiveTimeout,
/// When the server response, but with a incorrect status, such as 404, 503...
response,
/// When the request is cancelled, dio will throw a error with this type.
cancel,
/// Default error type, Some other Error. In this case, you can /// use the DioError.error if it is not null.
other,
}
import'package:dio_http/dio_http.dart';
import'package:dio_http/adapter.dart';
...
(dio.httpClientAdapter asDefaultHttpClientAdapter).onHttpClientCreate = (client) {
// config the http client
client.findProxy = (uri) {
//proxy all request to localhost:8888return'PROXY localhost:8888';
};
// you can also create a new HttpClient to dio// return HttpClient();
};