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

c# 发送post请求

作者:伪言   发布日期:2025-10-12   浏览:37

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

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

            // 创建要发送的数据对象
            var content = new StringContent(
                "{\"key1\":\"value1\", \"key2\":\"value2\"}",
                System.Text.Encoding.UTF8,
                "application/json"
            );

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

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

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"请求错误: {e.Message}");
            }
        }
    }
}

解释说明:

  1. HttpClient:用于发送HTTP请求和接收HTTP响应。
  2. StringContent:用于创建包含字符串内容的HTTP消息体。这里我们将JSON格式的数据作为请求体发送。
  3. PostAsync:异步发送POST请求到指定的URL。
  4. EnsureSuccessStatusCode:确保HTTP响应的状态码表示成功(200-299),否则抛出异常。
  5. ReadAsStringAsync:异步读取HTTP响应的内容为字符串。

如果需要发送其他类型的数据或处理更复杂的场景,可以根据具体需求调整代码。

上一篇:c# 加密解密

下一篇:c#websocket

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

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

Laravel 中文站