reqwest
库支持多种数据格式,包括但不限于以下几种:Content-Type
为application/json
,你可以发送和接收JSON格式的数据。Content-Type
为multipart/form-data
,你可以发送表单数据。Content-Type
为text/plain
,你可以发送纯文本数据。Content-Type
头来发送其他格式的数据。以下是一些示例代码,展示了如何使用reqwest
发送不同格式的数据:
use reqwest::Error; #[tokio::main] async fn main() -> Result<(), Error> { let client = reqwest::Client::new(); let json = serde_json::json!({ "key": "value" }); let response = client.post("https://example.com/api") .json(&json) .send() .await?; println!("Response: {:?}", response); Ok(()) }
use reqwest::Error; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Error> { let client = reqwest::Client::new(); let form_data = HashMap::from([ ("key1", "value1"), ("key2", "value2"), ]); let response = client.post("https://example.com/api") .form(&form_data) .send() .await?; println!("Response: {:?}", response); Ok(()) }
use reqwest::Error; #[tokio::main] async fn main() -> Result<(), Error> { let client = reqwest::Client::new(); let text = "This is a plain text request."; let response = client.post("https://example.com/api") .body(text) .send() .await?; println!("Response: {:?}", response); Ok(()) }
use reqwest::Error; use url::form_urlencoded::serialize; #[tokio::main] async fn main() -> Result<(), Error> { let client = reqwest::Client::new(); let form_data = serialize(&[ ("key1", "value1"), ("key2", "value2"), ])?; let response = client.post("https://example.com/api") .header(reqwest::header::CONTENT_TYPE, "application/x-www-form-urlencoded") .body(form_data) .send() .await?; println!("Response: {:?}", response); Ok(()) }
use reqwest::Error; use std::io::Cursor; #[tokio::main] async fn main() -> Result<(), Error> { let client = reqwest::Client::new(); let bytes = b"This is a byte stream request."; let body = Cursor::new(bytes); let response = client.post("https://example.com/api") .body(body) .send() .await?; println!("Response: {:?}", response); Ok(()) }
请注意,这些示例代码使用了tokio
作为异步运行时,并且假设你已经添加了必要的依赖项到你的Cargo.toml
文件中。