io icon indicating copy to clipboard operation
io copied to clipboard

Add function to create list of cookies from `set-cookie` header with multiple cookies

Open KiraResari opened this issue 2 years ago • 1 comments

Situation Some websites and API calls return multiple cookies at once, like this:

Set-Cookie: firstCookie=someCookieValue; Path=/; Secure; HTTPOnly
Set-Cookie: secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly

In the Dart Response object, they are grouped in a single map entry like this:

response
	headers
		"set-cookie": "firstCookie=someCookieValue; Path=/; Secure; HTTPOnly,secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly"

The Cookie class has a Cookie.fromSetCookieValue constructor, that will naturally not work with a situation where the set-cookie header entry contains multiple cookies.

Suggestion Add a static method List<Cookie> fromSetCookieValues(String value) to the Cookie that can be given a string containing multiple cookies, like this:

List<Cookie> cookiesInResponse = Cookie.fromSetCookieValues("firstCookie=someCookieValue; Path=/; Secure; HTTPOnly,secondCookie=anotherCookieValue; Path=/; Secure; HTTPOnly");

A practical example would then look like this:

Response responseWithMultipleCookies = await post(...);
List<Cookie> cookiesInResponse = Cookie.fromSetCookieValues(responseWithMultipleCookies.headers["set-cookie"]);

That function could look somewhat like this:

static List<Cookie> fromSetCookieValues(String value){
	List<Cookie> cookies = [];
	List<String> cookieStrings = value.split(",");
		for(var cookieString in cookieStrings){
			cookies.add(Cookie.fromSetCookieValue(cookieString));
		}
	}
	return cookies;
}

KiraResari avatar Jan 31 '23 09:01 KiraResari

This repo does nothing with requests / cookies. Anyway, you can find a plenty of packages that do exactly what you are asking, for example - sweet_cookie_jar

houdinihacker avatar Feb 27 '23 18:02 houdinihacker