如何在颤振上使用 cookie 发出 http 请求? [英] How do I make an http request using cookies on flutter?
本文介绍了如何在颤振上使用 cookie 发出 http 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在正确处理 cookie 的同时向远程服务器发出 http 请求(例如,存储服务器发送的 cookie,并在我发出后续请求时发送这些 cookie).保留所有 cookie 会很好
I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies
对于我正在使用的 http 请求
for http request I am using
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;
}
推荐答案
这里有一个示例,说明如何获取会话 cookie 并在后续请求中返回它.您可以轻松地调整它以返回多个 cookie.创建一个 Session
类并通过它路由所有 GET
和 POST
.
Here's an example of how to grab a session cookie and return it on subsequent requests. You could easily adapt it to return multiple cookies. Make a Session
class and route all your GET
s and POST
s through it.
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);
}
}
}
这篇关于如何在颤振上使用 cookie 发出 http 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文