在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的要求进行相应的参数配置,例如设置请求头、查询参数等。