gpt4 book ai didi

http - 如何使用 Reqwest 设置请求 header ?

转载 作者:可可西里 更新时间:2023-11-01 15:11:54 33 4
gpt4 key购买 nike

我需要使用 Reqwest 库向带有 cookie 的网站发出 GET 请求。我想出了如何发送 GET 请求:

let response = reqwest::get("http://example.com")?;

如何发送相同的请求但添加一些自定义 header ?

最佳答案

请求西0.10

开始于 crate's documentation ,我们看到:

For a single request, you can use the get shortcut method.

get 's documentation状态:

This function creates a new internal Client on each call, and so should not be used if making many requests. Create a Client instead.

Client 有一个 request方法指出:

Returns a RequestBuilder, which will allow setting headers and request body before sending.

RequestBuilder有一个 header method .这可以用作:

use reqwest::header::USER_AGENT;

let client = reqwest::Client::new();
let res = client
.get("https://www.rust-lang.org")
.header(USER_AGENT, "My Rust Program 1.0")
.send()
.await?;

How do I add custom headers?

如果您查看 header 的签名,你会看到它接受通用类型:

pub fn header<K, V>(self, key: K, value: V) -> RequestBuilder where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<Error>,

an implementation of TryFrom<&'a str> for HeaderName ,因此您可以使用字符串文字:

use reqwest; // 0.10.0
use tokio; // 0.2.6

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let client = reqwest::Client::new();
let res = client
.get("https://www.rust-lang.org")
.header("X-My-Custom-Header", "foo")
.send()
.await?;

Ok(())
}

关于http - 如何使用 Reqwest 设置请求 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911513/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com