.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);
    }
相关推荐
唐青枫2 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf4 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6254 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech4 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072555 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486665 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆5 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同5 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落5 天前
C# FileStream文件流读取文件
开发语言·c#