Set the User-Agent in a HTTP request using Rust reqwest

User Agent reqwest header

Dependencies

examples/reqwest-set-user-agent/Cargo.toml

[package]
name = "reqwest-set-user-agent"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }

The code

examples/reqwest-set-user-agent/src/main.rs


use reqwest::header::USER_AGENT;

fn main() {
    let client = reqwest::blocking::Client::new();

    let res = client
    .get("http://httpbin.org/headers")
    .send().unwrap();
    println!("{}", res.text().unwrap());

    let res = client
    .get("http://httpbin.org/headers")
    .header(USER_AGENT, "Rust Maven 1.42")
    .send().unwrap();
    println!("{}", res.text().unwrap());
}


The output

{
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "X-Amzn-Trace-Id": "Root=1-65b23d5c-7291d26c5121b8d160a837f9"
  }
}

{
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "Rust Maven 1.42",
    "X-Amzn-Trace-Id": "Root=1-65b23d5c-1376c1c654589f201d8f958c"
  }
}

Related Pages

Reqwest the HTTP client library of Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo