How to clear cookies in reqwest client? #2285
-
Hello, I have a request client built with cookie_store(true). At a certain point in the program, I would like all cookies to be cleared. Is there a way to achieve this without using the crate reqwest_cookie_store? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
use std::sync::{Arc, RwLock};
use cookie_store::{RawCookie, RawCookieParseError};
use reqwest::{blocking::ClientBuilder, header::HeaderValue};
struct CookieStoreWrapper(RwLock<cookie_store::CookieStore>);
impl CookieStoreWrapper {
fn clear(&self) {
self.0.write().unwrap().clear();
}
fn print_contents(&self) {
println!("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
let r = self.0.read().unwrap();
for c in r.iter_any() {
println!("{:?}", c);
}
println!("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
println!();
}
}
impl reqwest::cookie::CookieStore for CookieStoreWrapper {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
let mut w = self.0.write().unwrap();
let cs = cookie_headers.filter_map(|val| {
std::str::from_utf8(val.as_bytes())
.map_err(RawCookieParseError::from)
.and_then(RawCookie::parse)
.map(|c| c.into_owned())
.ok()
});
w.store_response_cookies(cs, url);
}
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
let r = self.0.read().unwrap();
let s = r
.get_request_values(url)
.map(|(name, value)| format!("{}={}", name, value))
.collect::<Vec<_>>()
.join("; ");
if s.is_empty() {
return None;
}
HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok()
}
}
fn main() {
let cs = cookie_store::CookieStore::new(None);
let cookie_store = Arc::new(CookieStoreWrapper(RwLock::new(cs)));
let c = ClientBuilder::new()
.cookie_provider(cookie_store.clone())
.build()
.unwrap();
c.get("https://google.com").send().unwrap();
println!("after GET");
cookie_store.print_contents();
cookie_store.clear();
println!("after clear()");
cookie_store.print_contents();
c.get("https://google.com").send().unwrap();
println!("after another GET");
cookie_store.print_contents();
} |
Beta Was this translation helpful? Give feedback.
reqwest_cookie_store
is a simple crate; if you want to avoid an extra dependency you can implement its functionality directly in your code, and usecookie_provider(cookie_store)
instead ofcookie_store(true)
. Note thatreqwest::cookies::Jar
usescookie_store::CookieStore
internally, so you already have a (transitive) dependency on thecookie_store
crate when you enable featurecookies
inreqwest
. See #1437 in regards to supporting this directly viareqwest::cookies::Jar
.