'Can't Access Cookie in HTTP Response with Flutter
I'm working on Flutter an app which will use Express based REST api. While implementing Cookie based sessions, I wanted to retrieve cookies from app with basic auth request but somehow I can't retrieve cookies in response. When I make the same request from Postman, there is no problem, cookies are setted automatically.
I am using HTTP package to make request and code is quite straightforward as below.
void login(String username, String password) async {
var url = 'http://$username:[email protected]:3333/auth';
var response = await http.get(url);
print('Response header: ${response.headers}');
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
There is no cookie in header or body of response.
Solution 1:[1]
If you want to get cookie values from HTTP response in flutter
String rawCookie = response.headers['set-cookie']!;
int index = rawCookie.indexOf(';');
String refreshToken = (index == -1) ? rawCookie : rawCookie.substring(0, index);
int idx = refreshToken.indexOf("=");
print(refreshToken.substring(idx+1).trim());
Solution 2:[2]
You have to call 'set-cookie' in header:
var cookies = response.headers['set-cookie'];
Solution 3:[3]
http package get and post actions are sending the request without cookies so you should put the cookies manually like this:
Response response = await get(url, headers: {'cookie': 'session_id=ufe1nfq69mdi67pnql6n1cs3cv; path=/; HttpOnly='});
But there is an easy way to do that without putting cookies manually by requests package
import 'package:requests/requests.dart';
// ...
// For example post some login request
var url = "http://yourApilink";
var body = Map<String, dynamic>();
body["username"] = username;
body["password"] = password;
var request = await Requests.post(url, body: body);
request.raiseForStatus();
if(request.statusCode==200) {
//Successful
var statusJson = json.decode(utf8.decode(request.bytes()));
//....
// Example for get some other actions
var url = "http://yourApilink";
var request = await Requests.get(url);
request.raiseForStatus();
print(request.json()['userid']);
if(request.statusCode==200) {
//Successful
var statusJson = json.decode(utf8.decode(request.bytes()));
//....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | saif aly |
Solution 2 | hoangquyy |
Solution 3 | wahid anvary |