How to persist a cookie in Dart?
829
To add cookies to hearders.
var cookie1 = 'xyz';
var cookie2 = 'abc';
var headers = {
"Content-Type": "application/json",
'Cookie': 'myCookie1=$cookie1; mycookie2=$cookie2',
};
For retrieving cookies
var cookiesData = response.headers['set-cookie'];
if (cookiesData != null) {
Map _cookies = _formatCookies(cookiesData);
// Do your logic
}
You will get this in a long String.
Here is what I personally use for formating
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;
}
Author by
Admin
Updated on December 28, 2022Comments
-
Admin over 1 year
i'm making an app in Flutter and i need to send a cookie on the header to access my web API.
However, i'm not having any sucesss.
Here is my code. How can i persist a Cookie in 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; } }
-
Akif about 3 yearsDoes this answer your question? How do I make an http request using cookies on flutter?
-
Admin about 3 yearsI am trying to reproduce in my code. But so far I haven't been able to
-
Akif about 3 yearsOk, then: stackoverflow.com/a/53687711/10659482
-
Admin about 3 yearsCould you show me in the code please?
-
-
Admin about 3 yearsYes, but how can i retreave this cookie from the server response?
-
Admin about 3 yearsWhat i need is obtain the cookie that the server is sending to me.
-
kallis about 3 years_format function I personally use for jwt tokens, not sure about the RegExp for other strings.
-
Admin about 3 yearsThank you for your answer. I'll try to reproduce here.