.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);
    }
相关推荐
z落落4 小时前
C# Task WaitAll、WaitAny、WhenAll、WhenAny
开发语言·c#
玖玥拾6 小时前
C# 语言进阶(十四)Unity UI界面开发 + 网络消息联动
服务器·开发语言·网络·ui·unity·c#·游戏引擎
czhc11400756637 小时前
712:Atta. cursor;ToggleButton
c#
AI行业学习7 小时前
OpenAI Codex 完整下载 & 安装指南(2026最新版)
linux·开发语言·python·.net·notepad++
玖玥拾8 小时前
C# 语言进阶(十三)网络 DLL 库分层设计
服务器·开发语言·网络·网络协议·c#
雪靡8 小时前
WPF PerMonitorV2 下的跨窗口问题
c#·wpf
苍狼唤9 小时前
SQL+C# 增删改查(练习)
数据库·sql·c#
非酋讨厌20 小时前
.NET 11 Preview 4 正式发布:Runtime-Async 全面启用、Process API 大幅扩展
.net
LibraJM1 天前
一种适合程序员的 Agent 协作方式的实践
c#·copilot·agents