美文网首页
Flutter 网络请求插件 -- dio

Flutter 网络请求插件 -- dio

作者: 不不不紧张 | 来源:发表于2022-07-20 18:26 被阅读0次

dio 是目前Flutter 最流行的网络请求插件
插件地址:https://pub.flutter-io.cn/packages/dio

官方给出的例子
import 'package:dio/dio.dart';
void getHttp() async {
  try {
    var response = await Dio().get('http://www.google.com');
    print(response);
  } catch (e) {
    print(e);
  }
}

使用方法

1. 初始化与相关设置

 BaseOptions options = BaseOptions(
      connectTimeout: 30000,
      receiveTimeout: 30000,
      responseType: ResponseType.json,
    );

dio = Dio(options);    

2. 请求方法

 /// Make http request with options.
  ///
  /// [path] The url path.
  /// [data] The request data
  /// [options] The request options.
  Future<Response<T>> request<T>(
    String path, {
    data,
    Map<String, dynamic>? queryParameters,
    CancelToken? cancelToken,
    Options? options,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  });

例子:

  Response response = await dio.request(
        url,//地址
        data: data, //参数
        queryParameters: queryParameters,
        options: checkOptions(method, options, checkToken),// 请求配置
        cancelToken: cancelToken //取消请求token
);

3. 请求配置
使用请求方法中的options参数进行配置
配置选项

Options({
    this.method, //请求方式 get,post
    this.sendTimeout,
    this.receiveTimeout,
    this.extra,
    this.headers,
    this.responseType,
    this.contentType,
    this.validateStatus,
    this.receiveDataWhenStatusError,
    this.followRedirects,
    this.maxRedirects,
    this.requestEncoder,
    this.responseDecoder,
    this.listFormat,
  });

选项中各个变量的注释

 /// Http method.
  String? method;

  /// Http request headers. The keys of initial headers will be converted to lowercase,
  /// for example 'Content-Type' will be converted to 'content-type'.
  ///
  /// The key of Header Map is case-insensitive, eg: content-type and Content-Type are
  /// regard as the same key.
  Map<String, dynamic>? headers;

  /// Timeout in milliseconds for sending data.
  /// [Dio] will throw the [DioError] with [DioErrorType.sendTimeout] type
  ///  when time out.
  int? sendTimeout;

  ///  Timeout in milliseconds for receiving data.
  ///
  ///  Note: [receiveTimeout]  represents a timeout during data transfer! That is to say the
  ///  client has connected to the server, and the server starts to send data to the client.
  ///
  /// [0] meanings no timeout limit.
  int? receiveTimeout;

  /// The request Content-Type. The default value is [ContentType.json].
  /// If you want to encode request body with 'application/x-www-form-urlencoded',
  /// you can set `ContentType.parse('application/x-www-form-urlencoded')`, 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`.
  ///
  /// If you want to receive the response data with original bytes,
  /// that's to say the type of [Response.data] will be List<int>, use `bytes`
  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;

  /// Whether receiving response data when http status code is not successful.
  /// The default value is true
  bool? receiveDataWhenStatusError;

  /// Custom field that you can retrieve it later in [Interceptor]、[Transformer] and the [Response] object.
  Map<String, dynamic>? extra;

  /// see [HttpClientRequest.followRedirects],
  /// The default value is true
  bool? followRedirects;

  /// Set this property to the maximum number of redirects to follow
  /// when [followRedirects] is `true`. If this number is exceeded
  /// an error event will be added with a [RedirectException].
  ///
  /// The default value is 5.
  int? maxRedirects;

  /// The default request encoder is utf8encoder, you can set custom
  /// encoder by this option.
  RequestEncoder? requestEncoder;

  /// The default response decoder is utf8decoder, you can set custom
  /// decoder by this option, it will be used in [Transformer].
  ResponseDecoder? responseDecoder;

  /// The [listFormat] indicates the format of collection data in request
  /// query parameters and `x-www-url-encoded` body data.
  /// Possible values defined in [ListFormat] are `csv`, `ssv`, `tsv`, `pipes`, `multi`, `multiCompatible`.
  /// The default value is `multi`.
  ListFormat? listFormat;

配置举例:

  • post请求
 options.method = "POST";
  • 请求头添加参数
 options.headers["abc"] = "123";
  • 表单请求
options.contentType = "application/x-www-form-urlencoded";

4. 请求拦截器
拦截器可以在dio对象发起请求和收到接口返回的数据时执行相应的方法,实现网络请求相关业务的统一处理

 dio = Dio(options);
 ///拦截器
 dio.interceptors.add(AuthTool());

其中AuthTool类继承于Interceptor,并在内部重写Interceptor类中的onRequest(发起请求),onResponse(收到数据),onError(请求出错)方法,就可以在dio对象发起请求,收到数据,和请求出错时调用对应的重写方法,实现对请求各个状态的统一处理

拦截器举例:

class AuthTool extends Interceptor {
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 统一添加请求头
    options.headers["abc"] = "123";
    return super.onRequest(options, handler);
  }

 @override
  onResponse(Response response, ResponseInterceptorHandler handler) {
    // 请求成功打印返回数据
    Log.json(json.encode(response.data), path: response.requestOptions.path);
    return super.onResponse(response, handler);
  }

 @override
  onError(DioError err, ErrorInterceptorHandler handler) {
    // 请求错误打印error
    Log.d("----------Error-----------");
    return super.onError(err, handler);
  }
}

欢迎指正

相关文章

网友评论

      本文标题:Flutter 网络请求插件 -- dio

      本文链接:https://www.haomeiwen.com/subject/mohyirtx.html