【C#】HttpClientでフォームデータ(x-www-form-urlencoded)をPOST送信する方法

目次

概要

Webページの一般的な入力フォーム(<form>タグ)と同じ形式である application/x-www-form-urlencoded でデータを送信する方法です。 FormUrlEncodedContent クラスを使用することで、キーと値のペアを自動的にURLエンコードし、適切な Content-Type ヘッダーを付与してPOSTリクエストを作成します。

仕様(入出力)

  • 入力: 送信したいデータ(キーと値のコレクション)。
  • 出力: サーバーからの応答(レスポンスボディ)。
  • 前提: .NET標準ライブラリ(System.Net.Http)を使用。

基本の使い方

Dictionary<string, string> にデータを詰め、FormUrlEncodedContent のコンストラクタに渡します。

var formData = new Dictionary<string, string>
{
    ["username"] = "user01",
    ["message"] = "Hello C#"
};

// 自動的にエンコード処理(スペース→+ など)が行われる
using var content = new FormUrlEncodedContent(formData);

// POST送信
var response = await client.PostAsync("https://example.com/api/login", content);

コード全文

ここでは「検索設定」のようなパラメータをフォーム形式で送信し、その結果を受け取るコンソールアプリケーションを作成します。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    // HttpClientは再利用する
    private static readonly HttpClient _httpClient = new HttpClient();

    static async Task Main()
    {
        // 送信先URL(テスト用)
        string url = "https://httpbin.org/post";

        Console.WriteLine($"送信先: {url}");

        try
        {
            // 1. 送信データの準備
            // キーと値をディクショナリで定義します
            var parameters = new Dictionary<string, string>
            {
                ["keyword"] = "network",
                ["encode"] = "UTF-8",
                ["maxsize"] = "20",
                ["comment"] = "C# & .NET" // 記号やスペースも自動でエンコードされます
            };

            // 2. コンテンツの作成 (application/x-www-form-urlencoded)
            // コンストラクタに渡すだけで、適切な形式に変換されます
            using var content = new FormUrlEncodedContent(parameters);

            Console.WriteLine("POSTデータを送信中...");

            // 3. POSTリクエストの実行
            using var response = await _httpClient.PostAsync(url, content);

            // ステータスコードの確認(失敗時は例外をスロー)
            response.EnsureSuccessStatusCode();

            // 4. 結果の表示
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("\n--- サーバーからの応答 ---");
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"通信エラー: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"エラー: {ex.Message}");
        }
    }
}

実行結果例(httpbin.orgの応答)

--- サーバーからの応答 ---
{
  "form": {
    "comment": "C# & .NET", 
    "encode": "UTF-8", 
    "keyword": "network", 
    "maxsize": "20"
  }, 
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded", 
    ...
  }, 
  ...
}

カスタムポイント

  • コレクションの初期化: C#のコレクション初期化子を使うと、キーバリューの定義がスッキリ書けます。
  • リストの送信: 同じキーで複数の値を送りたい場合(例: tag=csharp&tag=programming)、Dictionary ではなく List<KeyValuePair<string, string>> を使用して FormUrlEncodedContent に渡します。C#var multiValues = new List<KeyValuePair<string, string>> { new("tag", "csharp"), new("tag", "programming") }; var content = new FormUrlEncodedContent(multiValues);

注意点

  1. データサイズ: FormUrlEncodedContent はデータをすべてURLエンコードして文字列化するため、画像ファイルなどのバイナリデータや、極端に巨大なテキストデータの送信には向きません。その場合は MultipartFormDataContent を使用してください。
  2. 文字コード: デフォルトでは UTF-8 でエンコードされます。レガシーなシステム(Shift-JIS等)へ送信する必要がある場合は、自前で ByteArrayContent を作成し、エンコード済みバイト列をセットする必要があります。

応用

送信データの内容(エンコード結果)を確認する

実際にどのような文字列がサーバーに送られるかを確認する方法です。

using var content = new FormUrlEncodedContent(parameters);

// 文字列として読み出す(デバッグ用)
string encodedString = await content.ReadAsStringAsync();
Console.WriteLine(encodedString);
// 出力例: keyword=network&encode=UTF-8&maxsize=20&comment=C%23+%26+.NET

まとめ

Webフォームの送信をシミュレートする場合や、REST APIが application/x-www-form-urlencoded を要求する場合には、FormUrlEncodedContent を使用するのが標準的な手法です。キーと値のペアをDictionary等で用意して渡すだけで、面倒なURLエンコード処理や Content-Type ヘッダーの設定を自動的に行ってくれるため、安全かつ簡潔に実装することができます。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次