c#如何调用webapi接口
时间: 2023-12-02 15:03:20 浏览: 46
在 C# 中调用 Web API 接口通常需要使用 HttpClient 类。下面是一个简单的示例,演示如何使用 HttpClient 调用 Web API 接口:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
// 创建 HttpClient 实例
using var client = new HttpClient();
// 设置基地址
client.BaseAddress = new Uri("https://api.example.com/");
// 发送 GET 请求
HttpResponseMessage response = await client.GetAsync("users");
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
else
{
Console.WriteLine("请求失败: " + response.StatusCode);
}
}
}
```
上面的代码使用 HttpClient 发送一个 GET 请求到 https://api.example.com/users 接口,然后读取响应内容并输出。你可以根据需要修改代码,设置请求头、请求体、请求方法等。