C# HTTP POST 接口实现 JSON 数据格式通信
在 C# 中,可以使用 HttpClient 类来实现 HTTP POST 请求,并使用 JSON 数据格式进行通信。以下是一个示例代码:
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 httpClient = new HttpClient())
            {
                // 设置请求的内容类型为 application/json
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                // 构造要发送的 JSON 数据
                string json = '{"name":"John", "age":30}';
                // 发送 POST 请求并获取响应
                HttpResponseMessage response = await httpClient.PostAsync("http://example.com/api", new StringContent(json, Encoding.UTF8, "application/json"));
                // 确认请求是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseJson = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseJson);
                }
                else
                {
                    Console.WriteLine("请求失败: " + response.StatusCode);
                }
            }
        }
    }
}
在上述示例中,首先使用 HttpClient 类创建一个实例,并设置请求的内容类型为 'application/json'。然后,创建要发送的 JSON 数据字符串,并使用 StringContent 类将其作为请求的内容。接下来,使用 HttpClient 的 PostAsync 方法发送 POST 请求,并将响应保存在 HttpResponseMessage 对象中。最后,可以使用 ReadAsStringAsync 方法读取响应内容,并进行处理。
请注意替换示例中的 URL 和 JSON 数据为实际的接口地址和数据。
原文地址: https://www.cveoy.top/t/topic/pmfs 著作权归作者所有。请勿转载和采集!