LoginSignup
6
3

More than 5 years have passed since last update.

Rustのreqwestをつかってjsonをpostする

Posted at

概要

Rustのreqwestを使ってjsonをPOSTする方法

やり方

headerにContentType::json()を設定するのがみそ

// jsonを生成する際の変数
let param_a = "aaa";
let param_b = "bbb";
let param_c = 123;

// r#(Raw String Literal)でjsonを生成
let json_request = format!(
    r#"{{
  "paramA": "{}",
  "paramB": "{}",
  "paramC": {}
}}"#, param_a, param_b, param_c);

let client = reqwest::Client::new();
let mut res = client
    .post("http://example.com/sample/v1/SampleService")
    .header(ContentType::json())
    .body(json_request)
    .send()
    .unwrap();
let mut buf = String::new();
res.read_to_string(&mut buf)
    .expect("Failed to read response");
println!("{}", buf);
6
3
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
6
3