導入
GETが「取ってくる」なら、POSTは「作る・送る」、PUTは「更新する」、DELETEは「消す」。データを変更する操作です。ここではリクエストの組み立て方を学びます(実際の送信には受け側サーバーが必要なため、送信部分は読み物とし、組み立てを演習します)。
図解
flowchart LR
G["GET<br/>取得"] --- P["POST<br/>作成・送信"]
P --- U["PUT<br/>更新"]
U --- D["DELETE<br/>削除"]
style P fill:#e1f5fe
サンプル
using var client = new HttpClient();
// 送信するデータ(JSON)を作る
var newUser = new User("Taro", 20);
string json = JsonSerializer.Serialize(newUser);
// Content-Type を application/json にして本文を包む
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
Console.WriteLine($"送信本文: {json}");
Console.WriteLine($"Content-Type: {content.Headers.ContentType}");
// 送信本文: {"Name":"Taro","Age":20}
// Content-Type: application/json; charset=utf-8
// 実際の送信は次の形(受け側サーバーが必要):
// var res = await client.PostAsync(url, content); // 作成
// var res = await client.PutAsync(url, content); // 更新
// var res = await client.DeleteAsync(url); // 削除
record User(string Name, int Age);
- POST=作成・送信、PUT=更新、DELETE=削除
- 送信データは
StringContent(json, Encoding.UTF8, "application/json")で包む Content-Type: application/jsonで「これはJSONです」と伝える- POSTは冪等でない(二重送信で二重作成に注意)、GET/PUT/DELETEは冪等
演習
var order = new Order(1, 3200);
// TODO: order を JSON化し、StringContent(application/json)に包んで、
// その Content-Type を "application/json; charset=utf-8" と出力してください
___
record Order(int Id, int Total);
- 期待される出力:
application/json; charset=utf-8
ヒント1を見る
var content = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
ヒント2を見る
Console.WriteLine(content.Headers.ContentType);
まとめ
- POST=作成、PUT=更新、DELETE=削除
- 送信データは
StringContentでapplication/jsonとして包む - POSTは冪等でない(二重送信注意)
次回: 身元を伝える「認証ヘッダー」です。