3

how can I add set-cookie in Headers of Flutter API. I've used the following dart plugin:

Dart Plugin

I am following these links but couldn't add headers.

Flutter Cookbook

Stackoverflow Question

Below is my Code:

Future<Map> getApi() async {

    Map<String, String> headers = {};

    // HEADERS TO BE ADDED
    headers['Set-Cookie'] = "user_image=; Path=/";
    headers['Set-Cookie'] = "user_id=Administrator; Path=/";
    headers['Set-Cookie'] = "system_user=yes; Path=/";
    headers['Set-Cookie'] = "full_name=Administrator; Path=/";
    headers['Set-Cookie'] = "sid=123456789; Expires=Mon, 25-Feb-2019 11:01:39 GMT; Path=/";

    // API RESPONSE
    http.Response response = await http.get(
      apiUrl,
      headers: headers,
    );

    // CONVERT TO JSON AND MAP
    Map responseBody = convert.jsonDecode(response.body);

    return responseBody;
  }
Zain SMJ
  • 1,492
  • 7
  • 19
  • 33

3 Answers3

3

With the help of the solution given on this link I was able to solve my issue. Below is the HTTP request to add headers:

http.Response response = await http.get(
   apiUrl,
   headers: {'Cookie': 'sid=123456789'},
);

Thanks for the help guys.

Zain SMJ
  • 1,492
  • 7
  • 19
  • 33
0

This should do what you want

  HttpClient client = HttpClient();
  final request = await client.getUrl(Uri.parse("http://www.example.com/"));
  request.cookies
    ..add((Cookie('user_image', '')..path = '/'))
    ..add((Cookie('user_id', 'Administrator')..path = '/'))
    ..add((Cookie('system_user', 'yes')..path = '/'))
    ..add((Cookie('full_name', 'Administrator')..path = '/'))
    ..add((Cookie('sid', '123456789')..path = '/')
      ..expires = DateTime.utc(2019, 2, 25, 11, 01, 39));
  //request.write(...)
  final response = await request.close();
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

This Should Work ;

HttpClient client = HttpClient();
    final request = await client.send(http.Request("GET", Uri.parse("http://www.example.com/"))
            ..headers['Set-Cookie'] = "user_image=; Path=/"
            ..headers['Set-Cookie'] = "user_id=Administrator; Path=/"
            ..headers['Set-Cookie'] = "system_user=yes; Path=/"
            ..headers['Set-Cookie'] = "full_name=Administrator; Path=/"
            ..headers['Set-Cookie'] = "sid=123456789; Expires=Mon, 25-Feb-2019 11:01:39 GMT; Path=/"