简体   繁体   中英

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:$password@111.222.333.444: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.

You have to call 'set-cookie' in header:

var cookies = response.headers['set-cookie'];

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()));
//....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM