Reputation:
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;
}
}
Upvotes: 1
Views: 1496
Reputation: 21
String session = response.headers['set-cookie'].toString().split(";").first.split('=').last;
Upvotes: 0
Reputation: 133
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;
}
Upvotes: 2