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

CodeWithFlutter
2 Min Read

To make an HTTP request in Flutter and include cookies, you can use the http package and set the cookie header in the request.

Here’s an example of how you can make a GET request and send cookies in Flutter:

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

Future<http.Response> getData() async {
  var cookies = [
    'cookie1=value1',
    'cookie2=value2',
  ];
  
  var headers = {
    'Cookie': cookies.join('; '),
  };
  
  var response = await http.get('https://www.example.com', headers: headers);
  
  return response;
}

In this example, we’re using the http package to make a GET request to https://www.example.com. We’re setting the Cookie header in the request by concatenating an array of cookies using join('; ').

If you want to persist the cookies across multiple requests, you can store the cookies in a CookieJar and pass it to the Client class:

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

Future<http.Response> getData() async {
  var cookieJar = cookiejar.CookieJar();
  var client = http.Client()..cookieJar = cookieJar;

  var response = await client.get('https://www.example.com');

  return response;
}

In this example, we’re creating a CookieJar and setting it as the cookieJar property of the Client instance. This way, the cookies will be automatically included in all requests made with this Client instance.

Share this Article
Leave a comment