By default, httr2 uses a clean slate for every request meaning that cookies are not automatically preserved across requests. To preserve cookies, you must set a cookie file which will be read before and updated after each request.
Arguments
- req
A request.
- path
A path to a file where cookies will be read from before and updated after the request.
Examples
path <- tempfile()
httpbin <- request(example_url()) |>
req_cookie_preserve(path)
# Manually set two cookies
httpbin |>
req_template("/cookies/set/:name/:value", name = "chocolate", value = "chip") |>
req_perform() |>
resp_body_json()
#> $cookies
#> $cookies$chocolate
#> [1] "chip"
#>
#>
httpbin |>
req_template("/cookies/set/:name/:value", name = "oatmeal", value = "raisin") |>
req_perform() |>
resp_body_json()
#> $cookies
#> $cookies$chocolate
#> [1] "chip"
#>
#> $cookies$oatmeal
#> [1] "raisin"
#>
#>
# The cookie path has a straightforward format
cat(readChar(path, nchars = 1e4))
#> # Netscape HTTP Cookie File
#> # https://curl.se/docs/http-cookies.html
#> # This file was generated by libcurl! Edit at your own risk.
#>
#> 127.0.0.1 FALSE / FALSE 0 oatmeal raisin
#> 127.0.0.1 FALSE / FALSE 0 chocolate chip