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

c#调用post接口案例

作者:ˉ吻干迩的'泪   发布日期:2026-07-28   浏览:47

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

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

            // 创建要发送的数据对象
            var data = new
            {
                Key1 = "Value1",
                Key2 = "Value2"
            };

            // 将数据序列化为JSON格式
            string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(data);

            // 创建HttpContent对象并设置内容类型为application/json
            HttpContent content = new StringContent(jsonContent, 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请求。
  3. StringContent:将字符串内容封装为HTTP内容,这里指定了编码和内容类型(application/json)。
  4. EnsureSuccessStatusCode:确保HTTP响应状态码表示成功,否则会抛出异常。
  5. ReadAsStringAsync:异步读取响应内容为字符串。

此代码展示了如何使用C#中的HttpClient类来发送POST请求,并处理响应。

上一篇:c# array.sort

下一篇:c#post

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

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

Laravel 中文站