JoJo的个人博客

记录精彩的程序人生

目录
Flutter网络层 dio封装
/  

Flutter网络层 dio封装

依赖

dependencies:
  dio: ^x.x.x #请使用pub上的最新版本

dio用法

发起 GET 请求 :

Response response;
response = await dio.get("/test?id=12&name=wendu")
print(response.data.toString());

对于GET请求我们可以将query参数通过对象来传递,上面的代码等同于:

response = await dio.get("/test",queryParameters:{"id":12,"name":"wendu"})
print(response);

发起一个 POST 请求:

response = await dio.post("/test",data:{"id":12,"name":"wendu"})

发起多个并发请求:

response = await Future.wait([dio.post("/info"),dio.get("/token")]);

下载文件:

response = await dio.download("https://www.google.com/",_savePath);

发送 FormData:

FormData formData = new FormData.from({
   "name": "wendux",
   "age": 25,
});
response = await dio.post("/info", data: formData)

如果发送的数据是FormData,则dio会将请求header的contentType设为“multipart/form-data”。

通过FormData上传多个文件:

FormData formData = new FormData.from({
   "name": "wendux",
   "age": 25,
   "file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
   "file2": new UploadFileInfo(new File("./upload.txt"), "upload2.txt"),
     // 支持文件数组上传
   "files": [
      new UploadFileInfo(new File("./example/upload.txt"), "upload.txt"),
      new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
    ]
});
response = await dio.post("/info", data: formData)

charles代理设置

String charlesProxy = '169.254.124.128:8887';
bool isProxyChecked = true;
String proxy = charlesProxy;
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    (client) {
  client.badCertificateCallback =
      (X509Certificate cert, String host, int port) {
    return isProxyChecked && Platform.isAndroid;
  };
  client.findProxy = (url) {
    return isProxyChecked ? 'PROXY $proxy' : 'DIRECT';
  };
};

代码封装

import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:maskpark/util/bus.dart';
import 'package:maskpark/widget/toast.dart';

var http = Http();

class Http {
  var dio = Dio();
  var useCharles = false;

  ///使用charles需修改对应ip
  String charlesProxy = '169.254.124.128:8887';

  static Http _singleton = new Http._internal();

  factory Http() => _singleton;
  
  Http._internal() {
    dio.options.baseUrl = "http://rest.vtpm.starblingbling.com/";
    dio.options.connectTimeout = 20000;
    dio.options.receiveTimeout = 10000;

    dio.interceptors.add(LogInterceptor());
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
      options.headers.addAll({"token": "1231231231231"});
      return options;
    }, onResponse: (Response response) async {
      return response;
    }, onError: (DioError error) async {
      if (error.response?.statusCode == 401) {
        bus.emit("401");
      } else {
        if (error.type == DioErrorType.CONNECT_TIMEOUT ||
            error.type == DioErrorType.RECEIVE_TIMEOUT ||
            error.type == DioErrorType.DEFAULT) {
          toast.show("network error");
        } else {
          var errData = error.response?.data;
          if (errData != null) {
            toast.show(errData["message"]);
          }
        }
      }
      return error;
    }));

    ///charles抓包
    if (kDebugMode && useCharles) {
      bool isProxyChecked = true;
      String proxy = charlesProxy;
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) {
          return isProxyChecked && Platform.isAndroid;
        };
        client.findProxy = (url) {
          return isProxyChecked ? 'PROXY $proxy' : 'DIRECT';
        };
      };
    }
  }

  Future<Response<T>> get<T>(
      {String path, Map<String, dynamic> params, Options options}) {
    return dio.get<T>(path, queryParameters: params, options: options);
  }

  Future<Response<T>> post<T>({
    String path,
    body,
    Map<String, dynamic> params,
    bool isFormData = false,
    Options options,
  }) {
    if (isFormData) {
      FormData formData = new FormData.fromMap(body);
      body = formData;
    }
    return dio.post<T>(path,
        data: body, queryParameters: params, options: options);
  }

  Future<Response> download({
    String urlPath,
    savePath,
    Map<String, dynamic> queryParams,
    ProgressCallback progressCallback,
  }) {
    return dio.download(urlPath, savePath,
        queryParameters: queryParams, onReceiveProgress: progressCallback);
  }
}

参考文章

Flutter中文网


标题:Flutter网络层 dio封装
作者:SunnySky
地址:https://www.tianyang.pub/articles/2020/07/02/1593681534443.html

评论