How do I make an http request using cookies on flutter?

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 GETs and POSTs through it.

import 'package:http/http.dart' as http;

    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);
        }
      }
    }

Leave a Comment