0

I am using rest API in my flutter app. For further request I need JSESSIONID which I received from my profile API. I successful got response but I need guide to iterate cookie value.

I followed following steps:

final response = await http.get(
      strURL,
      headers: {
        "Authorization": basicAuth,
        "Content-Type": "application/json"
      },
    );

    String rawCookie = response.headers['set-cookie'];
    print('rawCookie $rawCookie');

As print raw cookie it is printing details:

flutter: rawCookie __cfduid=d5bbe3f8a131478a78ae996e636cca0401544177738; expires=Sat, 07-Dec-19 10:15:38 GMT; path=/; domain=.rayz.ch; HttpOnly,JSESSIONID=6AD6698C5BFC90F1D089696A955E6824; Path=/; HttpOnly

I can iterate it by substring but I want to iterate it with a proper way. So please guide me on this.

Code Hunter
  • 10,075
  • 23
  • 72
  • 102
  • you can start by coding a model class for rawCookie then you code a named constructor which will take your cookie string and populate your model properties – Saed Nabil Dec 07 '18 at 12:01
  • Possible duplicate of [How do I make an http request using cookies on flutter?](https://stackoverflow.com/questions/52241089/how-do-i-make-an-http-request-using-cookies-on-flutter) – Richard Heap Dec 08 '18 at 00:59
  • @RichardHeap In that question it is not mentioned how I can iterate that. There is only mentioned and I followed that one even to receive cookies. Now I want to iterate cookies separately. – Code Hunter Dec 08 '18 at 05:36
  • Using package http you need to split the cookies yourself by `split`ing the `String` on comma. – Richard Heap Dec 08 '18 at 22:38

2 Answers2

4

With package:http you need to split the cookie string yourself using String.split. If you want to use the underlying http client, that gives you a pre-parsed list of cookies, for example:

  HttpClient _httpClient = new HttpClient();
  HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  print(response.cookies); // this is a List<Cookie>
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
0

Here is my code which runs perfectly and if any key does not have value, then it shows range error. But as your doubt, this code is running fine.

var headersList = response.headers['set-cookie']!.split(";");
for(var kvPair in headersList){
  var kv = kvPair.split("=");
  var key = kv[0];
  var value = kv[1];

  if(key.contains("session_id")){
    print(value);
  }
}
  • 1
    `set-cookie` contains a comma-separated list, not a semicolon-separated list, of cookies. This won't work properly and it can't be fixed by simply replacing `;` with `,` because the cookie itself may also contain `,`. – Michel Jung Dec 29 '22 at 00:06