[C#] How to POST JSON Data with HttpClient

目次

Overview

This article covers the fundamental implementation for sending JSON-formatted data to a Web API. The process involves serializing a C# object into a JSON string and using the StringContent class to send a POST request with the Content-Type: application/json header.


Specifications (Input/Output)

  • Input: Data to be sent (C# objects or anonymous types).
  • Output: Server response results.
  • Operation: Serializes data to JSON and transmits it using UTF-8 encoding.
  • Prerequisite: Uses standard .NET libraries (System.Net.Http, System.Text.Json).

Basic Usage

The procedure consists of three steps: “Serialization” → “Creating StringContent” → “Transmission.” Specifying "application/json" as the third argument in the StringContent constructor is the most critical part.

// 1. Convert data to a JSON string
var data = new { Name = "Data", Value = 123 };
string json = JsonSerializer.Serialize(data);

// 2. Create HTTP content (Specifying Content-Type here)
using var content = new StringContent(json, Encoding.UTF8, "application/json");

// 3. Execute POST
await client.PostAsync("https://example.com/api", content);

Full Code Example

The following example creates an object containing search criteria, sends it as JSON to an API, and receives the response.

using System;
using System.Net.Http;
using System.Text; // Required for Encoding
using System.Text.Json; // Required for JSON serialization
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient _httpClient = new HttpClient();

    static async Task Main()
    {
        string url = "https://httpbin.org/post";
        Console.WriteLine($"Destination: {url}");

        // 1. Create data to be sent (using anonymous types)
        var requestData = new
        {
            TotalCount = 10,
            Filters = new[]
            {
                new { Keyword = "network", MaxSize = 20 },
                new { Keyword = "database", MaxSize = 50 }
            },
            Options = new
            {
                Encode = "UTF-8",
                IsRecursive = true
            }
        };

        try
        {
            // 2. JSON Serialization
            string jsonString = JsonSerializer.Serialize(requestData);
            
            Console.WriteLine("--- JSON to be Sent ---");
            Console.WriteLine(jsonString);

            // 3. Create StringContent
            // Arg 2: Encoding (usually UTF8)
            // Arg 3: Media type (must be "application/json" for the server to recognize it)
            using var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            // 4. Execute POST request
            using var response = await _httpClient.PostAsync(url, content);

            // Verify success
            response.EnsureSuccessStatusCode();

            // Display results
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("\n--- Response from Server ---");
            Console.WriteLine(responseBody);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Execution Result Example (Response from httpbin.org)

--- JSON to be Sent ---
{"TotalCount":10,"Filters":[{"Keyword":"network","MaxSize":20}...]}

--- Response from Server ---
{
  "json": {
    "Filters": [
      {
        "Keyword": "network", 
        "MaxSize": 20
      }, 
      ...
    ], 
    "TotalCount": 10
  }, 
  "headers": {
    "Content-Type": "application/json; charset=utf-8", 
    ...
  }
}

Customization Points

  • System.Text.Json vs. Newtonsoft.Json: While older projects may use JsonConvert.SerializeObject(data) (Newtonsoft), System.Text.Json is the recommended standard for .NET Core 3.1 and later.
  • Encoding: Encoding.UTF8 is the standard. If communicating with legacy systems (e.g., Shift-JIS), use Encoding.GetEncoding(...).

Important Notes

  • Media Type Specification: Forgetting to specify "application/json" in the StringContent constructor often results in the data being sent as text/plain, which causes the server to fail in parsing it as JSON.
  • Asynchronous Processing: While JsonSerializer.Serialize is fine for small data, consider using asynchronous serialization streams for massive datasets to maintain performance.

Advanced Application

PostAsJsonAsync (.NET 5+)

In .NET 5 and later, you can use the System.Net.Http.Json extension method to serialize and send data in a single step, eliminating the need to manually create StringContent.

using System.Net.Http.Json; // Required

// Pass the object directly
await _httpClient.PostAsJsonAsync(url, requestData);

Conclusion

To POST JSON data, the basic procedure involves using the StringContent class to build the request body. Explicitly specifying application/json in the constructor is a mandatory condition for the server to correctly interpret the data. For modern .NET versions, utilizing the more concise PostAsJsonAsync method is recommended.

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

この記事を書いた人

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

目次