简体   繁体   English

Dio dart/Flutter 获取和设置 cookie

[英]Dio dart/Flutter get and set cookie

I would like to do a set cookies, do a get request and after get the cookies.我想做一套 cookies,做一个获取请求,然后得到 cookies。 In python it will be this:在 python 中它将是这样的:

> import requests cookies = {'status': 'working','color':'blue'}
> response = session.get('https://google.com/', cookies=cookies)
> print(session.cookies.get_dict())

Do you know how to flutter it?你知道怎么flutter吗? I tried something like this but it doesn't seem to have a cookie in the response and the cookie doesn't seem to be sent我尝试了类似的方法,但响应中似乎没有 cookie,并且似乎没有发送 cookie

  Map<String, String> headers = {
      "status":"working",
      "color":"blue"   
    };
    final BaseOptions dioBaseOptions = BaseOptions(
    baseUrl: 'https://google.com',
    headers: {
      'Cookie': headers,
    },
    );
     dio = Dio(dioBaseOptions);
  var cookieJar=CookieJar();
  dio.interceptors.add(CookieManager(cookieJar));
var response = await dio.get('https://google.com/');

Cookie is set by a server in a response header and a browser sends it back in a request header. Cookie 由服务器在响应 header 中设置,浏览器在请求 header 中将其发回。

After receiving an HTTP request, a server can send one or more Set-Cookie headers with the response.在收到 HTTP 请求后,服务器可以发送一个或多个 Set-Cookie 标头作为响应。 The browser usually stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header.浏览器通常存储 cookie 并将其与 Cookie HTTP header 中的同一服务器的请求一起发送。

See Using HTTP cookies for details.有关详细信息,请参阅使用 HTTP cookies

CookieManager does this for dio and Flutter. CookieManagerdio和 Flutter 执行此操作。

To access Cookies in a dio response在 dio 响应中访问 Cookies

final cookies = response.headers['set-cookie']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM