C#中进行GET和POST API调用的方法

本文详细介绍了如何在C#中使用HttpClient进行GET和POSTAPI调用,包括GET请求的GetAsync方法和POST请求的PostAsync方法,以及如何将对象转换为JSON格式发送数据。
摘要由CSDN通过智能技术生成

在C#中进行GET和POST API调用的方法如下:
GET API调用:
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        using (var httpClient = new HttpClient())
        {
            // 发送GET请求
            HttpResponseMessage response = await httpClient.GetAsync("https://api.example.com/data");

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine($"请求失败: {response.StatusCode}");
            }
        }
    }
}

POST API调用:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        using (var httpClient = new HttpClient())
        {
            var requestBody = new { key1 = "value1", key2 = "value2" };
            var json = System.Text.Json.JsonSerializer.Serialize(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // 发送POST请求
            HttpResponseMessage response = await httpClient.PostAsync("https://api.example.com/data", content);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine($"请求失败: {response.StatusCode}");
            }
        }
    }
}

以上代码使用了HttpClient类来进行API调用。在GET请求中,我们使用GetAsync方法发送GET请求,并通过ReadAsStringAsync方法获取响应内容。在POST请求中,我们使用PostAsync方法发送POST请求,并将请求体以JSON格式发送。注意,这里使用了System.Text.Json命名空间中的JsonSerializer.Serialize方法来将对象转换为JSON字符串。
在实际使用中,可以根据API的要求进行相应的参数配置,例如设置请求头、查询参数等。
 

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BEN654776577

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值