The :cookies
plugin allows for cookies to be stored, managed and used in the context of a session:
http = HTTPX.plugin(:cookies)
response = http.get("https://example.com/setscookies") #=> "302 ... Location: https://example.com/another ... Set-Cookie: aadm...."
response = http.get(response.headers["location"]) #=> Sends the cookie information
This plugin also works seamlessly with the :follow_redirects
plugin, in that redirect responses setting a session cookie will be forwarded:
http = HTTPX.plugin(:cookies).plugin(:follow_redirects)
response = http.get("https://example.com/setscookies") #=> will redirect to "https://example.com/another" with cookies
A user can also initiate the cookie jar when starting the session as well.
You can do so using the :cookies
option. This can be:
:name
(and :value
) is defined);# 1.
http = HTTPX.plugin(:cookies).with_cookies("foo" => "bar")
http.get("https://example.com")
# 2.
http = HTTPX.plugin(:cookies).with_cookies([{ name: "foo", value: "bar" }])
http.get("https://example.com")
# 3.
http = HTTPX.plugin(:cookies)
response = http.get("https://example.com/setscookies")
# ... after a while
other_http = HTTPX.plugin(:cookies)
other_http.with_cookies(http.cookies)
other_http.get("https://example.com")
The extra options when defining a cookie correspond to the supported cookie attributes as per RFC6265:
:secure
: The “Secure” attribute, can be true
or false
(false
by default);:path
: The “Path” attribute ("/"
by default);:domain
: The “Domain” attribute (when not set, it’ll be sent in all session requests);:max_age
: The “Max-Age” attribute, can an integer (seconds) setting a lifetime for the cookie (when cookie expires, it’ll be dropped from the jar);:expires
: The “Expires” attribute, can be a Time
object, setting the moment after which the cookie is expired and is dropped from the jar);Next: Server Push