如何在Dart中持久化cookie?

hmtdttj4  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(108)

我正在Flutter中创建一个应用程序,我需要在头上发送一个cookie来访问我的Web API。
但是,我没有任何成功。
这是我的代码。我怎么能坚持饼干在 Flutter ?

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class XsrfToken {
  static Future<String> getXsrf(String getJwt) async {
    var url = 'https://www.myservice.com/api/v1/api.php';

    var decode = json.decode(getJwt);

    var header = {"Content-Type": "application/json"};

    Map params = {"token": decode};

    var _body = json.encode(params);

    var response = await http.post(url, headers: header, body: _body);

    print('Responde status ${response.statusCode}');
    print('Responde body ${response.body}');

    var xsrf = response.body;

    var prefs = await SharedPreferences.getInstance();
    prefs.setString("TokenXSRF", xsrf);

    return xsrf;
  }
}

字符串

aiazj4mn

aiazj4mn1#

向hearders添加cookie。

var cookie1 = 'xyz';
var cookie2 = 'abc';

var headers =  {
          "Content-Type": "application/json",
          'Cookie': 'myCookie1=$cookie1; mycookie2=$cookie2',
        };

字符串
用于检索Cookie

var cookiesData = response.headers['set-cookie'];
if (cookiesData != null) {
    Map _cookies = _formatCookies(cookiesData);
    // Do your logic
}


你会得到这个在一个长串。
下面是我个人用来格式化的

Map _formatCookies(String cookiesData) {
  Map cookies = {};

  if (cookiesData.contains('cookie1')) {
    List at = RegExp(r'(cookie1)(.*?)[^;]+').stringMatch(cookiesData).split('=');
    cookies['cookie1'] = at[1];
  }

  if (cookiesData.contains('cookie2')) {
    List rt = RegExp(r'(cookie2)(.*?)[^;]+').stringMatch(cookiesData).split('='); 
    cookies['cookie2'] = rt[1];
  }

  return cookies;
}

wlzqhblo

wlzqhblo2#

String session = response.headers['set-cookie'].toString().split(“;“).first.split('=').last;

相关问题