美文网首页
Dio二次封装

Dio二次封装

作者: Jean_Lina | 来源:发表于2021-12-02 14:39 被阅读0次
  • HttpRequest封装
import 'package:dio/dio.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(
    baseUrl: HttpConfig.base_url,
    connectTimeout: HttpConfig.connect_time,
  );
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(
    String url, {
    String method = 'get',
    Interceptor? interceptor,
    Map<String, dynamic>? params,
  }) async {
    final options = Options(method: method);
    Interceptor defaultInterceptor =
        InterceptorsWrapper(onRequest: (options, handler) {
      print("onRequest 请求拦截:" + options.headers.toString());
      return handler.next(options);
    }, onResponse: (response, handler) {
      print("onResponse 响应拦截:" + response.toString());
      return handler.next(response);
    }, onError: (DioError error, handler) {
      print("DioError 错误拦截:" + error.toString());
      return handler.next(error);
    });
    List<Interceptor> inters = [defaultInterceptor];
    if (interceptor != null) {
      inters.add(interceptor);
    }
    dio.interceptors.addAll(inters);
    try {
      final response =
          await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch (error) {
      return Future.error(error.message);
    }
  }
}
  • HttpConfig封装
class HttpConfig {
  static const String base_url = 'https://httpbin.org';
  static const int connect_time = 5000;
}
  • 发起网络请求:
HttpRequest.request('/post', method: 'post', params: {'name': 'why'})
        .then((value) {
      print('网络请求结束: $value');
    });

相关文章

网友评论

      本文标题:Dio二次封装

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