cookie持久化设置

由于公司APP开发网络请求涉及到cookie的的运用,自己抽点时间研究了一下,flutter dio中cookie的设置
dio_cookie_manager
cookie_jar

1.获取cookie,存储(持久化处理),用到两个库,本身dio就是基于cookie_jar来管理cookie的

import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';

2.把cookie存储到APP的内存当中,下次请求的时候就会使用到,这里用到了这个库 path_provider,来获取路径,这里是在自己创建的dio基类HttpUtil中设置的

 ///设置cookie
  static void _getLocalFile() async {
    // 获取文档目录的路径
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String dir = appDocDir.path + "/.cookies/";
    print( 'cookie路径地址:' + dir);
    var cookieJar = PersistCookieJar(dir: dir);
    _dio.interceptors.add(CookieManager(cookieJar));
  }

HttpUtil代码

class HttpUtil {
  static final HttpUtil _singleton = HttpUtil._internal();

  static HttpUtil get instance => HttpUtil();

  factory HttpUtil() {
    return _singleton;
  }

  static Dio _dio;

  Dio getDio() {
    return _dio;
  }

  HttpUtil._internal() {
    var options = BaseOptions(
      connectTimeout: 15000,
      receiveTimeout: 15000,
      responseType: ResponseType.plain,
      contentType: "application/x-www-form-urlencoded",
      baseUrl: "http://47.98.xxxxxx",
    );
    _dio = Dio(options);
    print('' * 20);
    _getLocalFile();
    print( 'cookie路径地址');
    /// Fiddler抓包代理配置 https://www.jianshu.com/p/d831b1f7c45b
    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.findProxy = (uri) {
        //proxy all request to localhost:8888
        return "PROXY 192.168.1.198:8888";
      };
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
    };
  }

  ///设置cookie
  static void _getLocalFile() async {
    // 获取文档目录的路径
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String dir = appDocDir.path + "/.cookies/";
    print( 'cookie路径地址:' + dir);
    var cookieJar = PersistCookieJar(dir: dir);
    _dio.interceptors.add(CookieManager(cookieJar));
  }

}

String requestParams(Map value) {
  return "jsonStr=${json.encode(value)}";
}

String getErrorMessage(DioErrorType type) {
  switch (type) {
    case DioErrorType.DEFAULT:
      return "网络不可用,请检查网络";
    case DioErrorType.CONNECT_TIMEOUT:
      return "网络连接超时,请重试";
    case DioErrorType.SEND_TIMEOUT:
      return "数据发送超时,请重试";
    case DioErrorType.RECEIVE_TIMEOUT:
      return "数据接受超时,请重试";
    case DioErrorType.RESPONSE:
      return "无法连接服务器,请重试";
    case DioErrorType.CANCEL:
      return "网络连接已取消";
    default:
      return "";
  }
}

3.在 runApp 时调用:HttpUtil.instance;

你可能感兴趣的:(cookie持久化设置)