本文介绍了如何在Flutter上使用Cookie发出http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在正确处理cookie的同时向远程服务器发出http请求(例如,存储服务器发送的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);
}
}
}
这篇关于如何在Flutter上使用Cookie发出http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!