5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust の http クライアントの使い方 (Post)

5
Last updated at Posted at 2020-07-14

次のページを参考にしました。
Crate reqwest

プロジェクトの作成

cargo new http_post --bin
Cargo.toml
[package]
name = "http_post"
version = "0.1.0"
edition = "2024"

#

[dependencies]
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json"] }
serde_json = "1.0"

src/main.rs
// --------------------------------------------------------------------
/*
	http_post.rs

					Jul/15/2020
*/
// --------------------------------------------------------------------
use std::collections::HashMap;

# [tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
	eprintln!("*** 開始 ***");
	let mut map = HashMap::new();
	map.insert("user", "jiro");
	map.insert("password", "123456");

	let client = reqwest::Client::new();
	let url = "https://httpbin.org/post";
	let resp = client.post(url)
		.json(&map)
		.send()
		.await?;

//	println!("{:#?}", resp);

	let body = resp.text().await? ;
//	println!("{:#?}", body);

	let json: serde_json::Value = serde_json::from_str(&body)?;

	let obj = json.as_object().unwrap();

	for (key,value) in obj.iter() {
		println!("{}\t{}",key,value);
		}

	eprintln!("*** 終了 ***");
	Ok(())
}

// --------------------------------------------------------------------

コンパイル

cargo build

実行結果

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/http_post`
*** 開始 ***
args	{}
data	"{\"user\":\"jiro\",\"password\":\"123456\"}"
files	{}
form	{}
headers	{"Accept":"*/*","Content-Length":"35","Content-Type":"application/json","Host":"httpbin.org","X-Amzn-Trace-Id":"Root=1-691d6ca9-574a76b660ffe4151fdb70f5"}
json	{"password":"123456","user":"jiro"}
origin	"219.126.140.210"
url	"https://httpbin.org/post"
*** 終了 ***

確認したバージョン

$ rustc --version
rustc 1.91.1 (ed61e7d7e 2025-11-07) (Arch Linux rust 1:1.91.1-2)

$ cargo --version
cargo 1.91.1 (ea2d97820 2025-10-10) (Arch Linux rust 1:1.91.1-2)
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?