Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# post json

作者:偶然\寥寂り   发布日期:2025-07-10   浏览:8

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            // 设置请求的URL
            string url = "https://example.com/api/endpoint";

            // 创建要发送的JSON对象
            var jsonContent = new
            {
                Property1 = "value1",
                Property2 = 2,
                Property3 = true
            };

            // 将JSON对象序列化为字符串
            string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonContent);

            // 创建HttpContent对象,设置内容类型为application/json
            HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            try
            {
                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync(url, content);

                // 确保请求成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response: " + responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("Request error: " + e.Message);
            }
        }
    }
}

解释说明:

  1. HttpClient:用于发送HTTP请求和接收HTTP响应。
  2. PostAsync:发送POST请求到指定的URL。
  3. StringContent:将JSON字符串封装为HTTP内容,并指定内容类型为application/json
  4. JsonConvert.SerializeObject:使用Newtonsoft.Json库将C#对象序列化为JSON字符串。
  5. EnsureSuccessStatusCode:确保HTTP响应状态码表示成功(如200、201等),否则抛出异常。
  6. ReadAsStringAsync:读取HTTP响应的内容并转换为字符串。

这个示例展示了如何在C#中通过POST方法发送JSON数据到服务器,并处理服务器返回的响应。

上一篇:c# string转byte[]

下一篇:c# gui

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# 取字符串最后一个字符

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站