gpt4 book ai didi

android - 如何在 Flutter 上使用 cookie 发出 http 请求?

转载 作者:IT老高 更新时间:2023-10-28 12:31:48 27 4
gpt4 key购买 nike

我想在正确处理 cookie 的同时向远程服务器发出 http 请求(例如,存储服务器发送的 cookie,并在我发出后续请求时发送这些 cookie)。最好保留所有 cookie

对于我正在使用的 http 请求

static Future<Map> postData(Map data) async {
http.Response res = await http.post(url, body: data); // post api call
Map data = JSON.decode(res.body);
return data;
}

最佳答案

这是一个如何获取 session cookie 并在后续请求中返回它的示例。您可以轻松调整它以返回多个 cookie。创建一个 Session 类并通过它路由所有 GETPOST

class Session {
Map<String, String> headers = {};

Future<Map> get(String url) async {
http.Response response = await http.get(url, headers: headers);
updateCookie(response);
return json.decode(response.body);
}

Future<Map> post(String url, dynamic data) async {
http.Response response = await http.post(url, body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}

void updateCookie(http.Response response) {
String rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}

关于android - 如何在 Flutter 上使用 cookie 发出 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241089/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com