.Net Framework请求外部Api

要在.NET Framework 4.5中进行外部API的POST请求,你可以使用HttpClient类。

1. Post请求

csharp 复制代码
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // 创建一个HttpClient实例
        using (HttpClient client = new HttpClient())
        {
            try
            {
                // 创建请求的内容
                var requestData = new { Name = "John", Age = 30 };
                var content = new StringContent(JsonConvert.SerializeObject(requestData), System.Text.Encoding.UTF8, "application/json");

                // 发起POST请求并获取响应
                HttpResponseMessage response = await client.PostAsync("https://api.example.com/some-endpoint", content);

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

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();

                // 处理响应数据
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                // 处理请求异常
                Console.WriteLine($"请求异常: {e.Message}");
            }
        }
    }
}

另外,post传参还有另外一种方式,使用FormUrlEncodedContent

csharp 复制代码
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
 {
     {"empid", "E01930"},
 });

2. Get请求

cpp 复制代码
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
// 设置API的URL
string apiUrl = "http://nhbsapt01:801/accountreviewautoupdate";
string fullUrl = apiUrl + "?empid=" + "A00001";

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

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

    // 读取响应内容
    string responseBody = response.Content.ReadAsStringAsync().Result;

    // 处理响应数据
    Console.WriteLine(responseBody);
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

3. 奇葩(post请求url传参)

csharp 复制代码
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
    // 设置API的URL
    string apiUrl = "http://nhbsapt01:801/accountreviewautoupdate";
    string fullUrl = apiUrl + "?empid=" + "A00001";

    // 构造要发送的参数
    var postData = new Dictionary<string, string>
    {
        { "empid", "A00001" },
    };

    // 将参数转换为表单编码格式
    var content = new FormUrlEncodedContent(postData);

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

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

        // 读取响应内容
        string responseBody = response.Content.ReadAsStringAsync().Result;

        // 处理响应数据
        Console.WriteLine(responseBody);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
相关推荐
BruceNeter25 分钟前
C# 使用StackExchange.Redis实现分布式锁的两种方式
redis·c#
白熊1883 小时前
【计算机视觉】CV实战项目 -深度解析PaddleSegSharp:基于PaddleSeg的.NET图像分割解决方案
人工智能·计算机视觉·.net
互联网打工人no13 小时前
.NET8 依赖注入组件
开发语言·c#·.net·ioc
程序设计实验室11 小时前
一次小而美的重构:使用 C# 在 Avalonia 中生成真正好看的词云
c#
电商api接口开发12 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
HelloRevit15 小时前
.NET 10 中的新增功能
.net
o0向阳而生0o15 小时前
28、.NET 中元数据是什么?
microsoft·c#·.net
niuTaylor16 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#
军训猫猫头16 小时前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
冰茶_18 小时前
.NET MAUI 发展历程:从 Xamarin 到现代跨平台应用开发框架
学习·microsoft·微软·c#·.net·xamarin