.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);
    }
相关推荐
唐青枫3 小时前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
我好喜欢你~10 小时前
C#---StopWatch类
开发语言·c#
一阵没来由的风14 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
zzzhpzhpzzz17 小时前
Win10快速安装.NET3.5
.net·win10
许泽宇的技术分享19 小时前
Windows MCP.Net:基于.NET的Windows桌面自动化MCP服务器深度解析
windows·自动化·.net
一枚小小程序员哈20 小时前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM1 天前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
cimeo1 天前
【C 学习】06-算法&程序设计举例
c#
百锦再1 天前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
WYH2872 天前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#