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?

More than 3 years have passed since last update.

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

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 = "2018"

#

[dependencies]
reqwest = { version = "0.10", features = ["json"] }
tokio = { version = "0.2", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
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 [unoptimized + debuginfo] target(s) in 0.06s
     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-5f0eb9e1-064b695a2db532c4d57d894e"}
json	{"password":"123456","user":"jiro"}
origin	"219.126.137.21"
url	"https://httpbin.org/post"
*** 終了 ***

次のバージョンで確認しました。

$ rustc --version
rustc 1.43.0

$ cargo --version
cargo 1.43.0
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?