How do i set Cookie to Http Request

Last updated Oct 12, 2021

In this flutter example we will learn how to set cookie to request call in flutter. Cookies need few flags  which will set to enforce check security for http only and secure. 

To set cookie in flutter we will follow below steps

  • Call API to Get Cookie values
  • Add cookie values to request params
  • Call Api calls

In this flutter cookie example we will use Dio network library

 

Let's get started

Step 1: Create flutter application in Android studio

Step 2: Add dependencies to pubspec.yaml file

Step 3: Now implement logic to set cookie for request

 

For get method we have passed cookie in header

headers: token != null ? {'cookie': token} : null,

 

For Post method we will pass inside token attribute we will set cookie data

Map<String,dynamic>cookies=new Map();
cookies['cookie']="pass your cookie details";

 

String token: cookies.toString(),

import 'package:dio/dio.dart';
import 'dart:convert';
class ApiClient {
  final Dio _dio;
  final Connectivity _connectivity;

  const ApiClient(this._dio, this._connectivity);

  dynamic get(
    String path, {
    String? token,
    Map<String, dynamic>? query,
  }) async {
    dynamic response;
    try {
      print('[API-REQ]-> $path: $query');
      response = await _dio.get(
        path,
        queryParameters: query,
        options: Options(
          method: 'GET',
          headers: token != null ? {'cookie': token} : null,
        ),
      );
    } catch (e) {
      print('try-catch: $e');
      throw Exception(e);
    }

    if (response?.statusCode == 200) {
      return response.data;
    } else if (response?.statusCode == 401) {
      throw UnauthorisedException();
    } else {
      throw Exception(response.statusMessage);
    }
  }
Map<String,dynamic>cookies=new Map();
cookies['cookie']="pass your cookie details";
  dynamic post(
    String path, {
    String token: cookies.toString(),
    required Map<dynamic, dynamic>? body,
    bool fakeData: false,
  }) async {
    
    dynamic response;
    try {
      if (await _connectivity.checkConnectivity() == ConnectivityResult.none) {
        throw NetworkException(TranslationConstants.connectionError);
      }
      try {
       
        response = await _dio.post(
          path,
          data: body,
          options: Options(
            method: 'POST',
            headers: {'Authorization': token},
          ),
        );
      } catch (e) {
        throw InvalidException(TranslationConstants.serverError);
      }
    } on PlatformException catch (_) {
      throw NetworkException(TranslationConstants.connectionError);
    }
    print('Status-Code: ${response.statusCode}');
    print('Response: $response');
    if (response.statusCode == 200 || response.statusCode == 201) {
      return response.data;
    } else if (response.statusCode == 203) {
      throw InvalidException(response.data['message']);
    } else if (response.statusCode == 401) {
      throw UnauthorisedException();
    } else {
      throw Exception(response.statusMessage);
    }
  }
  }

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1739 Views