How to submit JSON data using POST in C#?
In C#, the HttpClient class can be used to send HTTP requests and submit JSON data. Below is an example code:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace HttpClientExample
{
class Program
{
static async Task Main(string[] args)
{
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
// 设置请求的内容类型为application/json
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
// 构造要发送的JSON数据
var json = "{\"name\":\"John\", \"age\":30}";
// 构造HTTP请求内容
var content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送POST请求
var response = await client.PostAsync("http://example.com/api/endpoint", content);
// 获取响应内容
var responseString = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(responseString);
}
}
}
}
The code above utilizes the HttpClient class to send a POST request with the content being a JSON string. Initially, we set the content type of the request as application/json using the HttpClient.DefaultRequestHeaders property. Next, we construct a StringContent object to encapsulate the JSON data to be sent, specifying the content type as application/json. Then, we use the HttpClient.PostAsync method to send the POST request, passing the request URL and content. Finally, we can retrieve the response content using the HttpResponseMessage.Content property and read it as a string using the ReadAsStringAsync method.