Sample code for 30+ languages & platforms
Rust

Adding Cookies to an HTTP Request

See more HTTP Examples

Demonstrates how to add one or more cookies to an HTTP request.

Chilkat Rust Downloads

Rust

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let http = chilkat::Http::new();

// The Cookie header field has this format:
// Cookie: name1=value1 [; name2=value2] ...

// Build an HTTP POST request:
let req = chilkat::HttpRequest::new();
req.set_from_url("http://www.chilkatsoft.com/echoPost.asp");
req.set_http_verb("POST");

req.add_param("param1", "value1");
req.add_param("param2", "value2");

// To add cookies to any HTTP request sent by a Chilkat HTTP method
// that uses an HTTP request object, add the cookies to the
// request object by calling AddHeader.  

// Add two cookies:
req.add_header("Cookie", "user=\"mary\"; city=\"Chicago\"");

// Send the HTTP POST.  
// (The cookies are sent as part of the HTTP header.)

let domain = "www.chilkatsoft.com".to_string();
let port = 80;
let ssl = false;
let resp = chilkat::HttpResponse::new();
if http.http_s_req(&domain, port, ssl, &req, &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

// Display the HTML body of the response.
if resp.status_code() == 200 {
    // Show the last HTTP request header sent, which should include
    // our cookies...
    println!("{}", http.last_header());
} else {
    println!("HTTP Response Status = {}", resp.status_code());
}

println!("---------------------");

// Some Chilkat HTTP methods do not use an HTTP request object. 
// For these methods, such as for QuickGetStr, cookies (or any HTTP request header) 
// are added by calling SetRequestHeader.  
http.set_request_header("Cookie", "user=\"mary\"; city=\"Chicago\"");

let html = http.quick_get_str("http://www.w3.org/").unwrap_or_default();
if !http.last_method_success() {
    println!("{}", http.last_error_text());
} else {
    // Show the last HTTP request header sent, which should include
    // our cookies...
    println!("{}", http.last_header());
}