Code Hunter
Code Hunter

Reputation: 11208

How do I can iterate cookie values from http response?

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.

Upvotes: 0

Views: 4104

Answers (2)

Dhruva Shaiva
Dhruva Shaiva

Reputation: 19

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

Upvotes: 0

Richard Heap
Richard Heap

Reputation: 51682

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>

Upvotes: 4

Related Questions