在 Flutter 中使用 Cookie 发布请求

Dev*_*977 2 cookies post request dart flutter

我正在尝试将 Cookie 添加到我的请求中:

在这里我收到csrftoken一个GET请求:

 Future<String> getCsrftoken() async{
       var response = await http.get(Uri.encodeFull('http://test/accounts/login/'));
       var csrftoken = response.headers.remove('set-cookie').substring(10,74); //csrf 
       64 chars
       return csrftoken;
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我尝试使用包Dio执行POST( application/x-www-form-urlencoded) 请求 。

getSessionId() async {
  var csrf = await getCsrftoken();
  var cj = new CookieJar();
  List<Cookie> cookies = [new Cookie("csrftoken", csrf)];
  cj.saveFromResponse(Uri.parse("http://test/accounts/login/"), cookies);
  List<Cookie> results = cj.loadForRequest(Uri.parse("http://test/accounts/login/"));
  var dio = new Dio(new Options(
      baseUrl: "http://test/accounts/login/",
      connectTimeout: 5000,
      receiveTimeout: 100000,
      // 5s
      headers: {
      },
      contentType: ContentType.JSON,
      // Transform the response data to a String encoded with UTF8.
      // The default value is [ResponseType.JSON].
      responseType: ResponseType.PLAIN
  ));

  Response<String> response;

  response = await dio.post("",
    data: {
      "username": "username",
      "password": "password",
      "csrfmiddlewaretoken" : getCsrftoken()
    },
    // Send data with "application/x-www-form-urlencoded" format
    options: new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded")),
  );
  print(response.statusCode);
}
Run Code Online (Sandbox Code Playgroud)

我得到 403 状态代码,因为我需要添加为 cookie csrftoken

我应该如何进行?

Rya*_*n C 5

来自Dio Dart API 文档

饼干管理器

您可以使用 cookieJar 管理请求/响应 cookie。

dio cookie 管理 API 基于撤回的 cookie_jar。

您可以创建 CookieJar 或 PersistCookieJar 来自动管理 cookie,dio 默认使用 CookieJar,将 cookie 保存在 RAM 中。如果要持久化cookie,可以使用PersistCookieJar类,示例代码如下:

var dio = new Dio();
dio.cookieJar=new PersistCookieJar("./cookies");
Run Code Online (Sandbox Code Playgroud)

PersistCookieJar 是一个 cookie 管理器,它实现了 RFC 中声明的标准 cookie 策略。PersistCookieJar 将 cookie 保存在文件中,因此如果应用程序退出,cookie 始终存在,除非显式调用 delete。

有关 cookie_jar 的更多详细信息,请参阅:https : //github.com/flutterchina/cookie_jar