当前位置:实例文章 » C#开发实例» [文章]C# Http 请求接口 Get / Post

C# Http 请求接口 Get / Post

发布人:shili8 发布时间:2024-03-19 11:30 阅读次数:76

在C#中,我们可以使用HttpClient类来发送Http请求并与接口进行通信。在这里,我们将展示如何使用HttpClient类来发送Get和Post请求。

首先,我们需要在项目中引用System.Net.Http命名空间。

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


接下来,我们将展示如何发送Get请求并获取接口返回的数据。

csharppublic async Task<string> GetRequest(string url)
{
 using (HttpClient client = new HttpClient())
 {
 HttpResponseMessage response = await client.GetAsync(url);
 if (response.IsSuccessStatusCode)
 {
 string result = await response.Content.ReadAsStringAsync();
 return result;
 }
 else {
 throw new HttpRequestException($"Failed to get data from {url}. Status code: {response.StatusCode}");
 }
 }
}


在上面的代码中,我们创建了一个HttpClient实例,并使用GetAsync方法发送Get请求。如果请求成功,我们将返回接口返回的数据;如果请求失败,我们将抛出一个HttpRequestException异常。

接下来,我们将展示如何发送Post请求并向接口发送数据。

csharppublic async Task<string> PostRequest(string url, string data)
{
 using (HttpClient client = new HttpClient())
 {
 StringContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
 HttpResponseMessage response = await client.PostAsync(url, content);
 if (response.IsSuccessStatusCode)
 {
 string result = await response.Content.ReadAsStringAsync();
 return result;
 }
 else {
 throw new HttpRequestException($"Failed to post data to {url}. Status code: {response.StatusCode}");
 }
 }
}


在上面的代码中,我们创建了一个StringContent实例来存储要发送的数据,并使用PostAsync方法发送Post请求。如果请求成功,我们将返回接口返回的数据;如果请求失败,我们将抛出一个HttpRequestException异常。

通过以上示例,我们可以看到如何使用C#中的HttpClient类来发送Get和Post请求与接口进行通信。在实际开发中,我们可以根据接口的需求来调整请求的参数和数据格式。

其他信息

其他资源

Top