c#

C#调用WebAPI支持GET和POST吗

小樊
204
2024-07-10 00:17:23
栏目: 编程语言

是的,C#可以通过使用HttpClient类来调用WebAPI,并支持GET和POST请求。以下是一个简单的示例:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync("https://api.example.com/api/resource");
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);

            // 发送POST请求
            var postData = new { key1 = "value1", key2 = "value2" };
            response = await client.PostAsJsonAsync("https://api.example.com/api/resource", postData);
            result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

在上面的示例中,我们使用HttpClient类发送了一个GET请求和一个POST请求,并获取了响应内容。GET请求使用GetAsync方法,POST请求使用PostAsJsonAsync方法。您可以根据需要更改请求的地址、数据和方法。

0
看了该问题的人还看了