Rust的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
文件中。