androidhttpcookiesflutter

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


I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies

for http request I am using

static Future<Map> postData(Map data) async {
  http.Response res = await http.post(url, body: data); // post api call
  Map data = JSON.decode(res.body);
  return data;
}

Solution

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