在C#中,使用HttpClient
类进行网络请求和数据交换是一个常见的做法。HttpClient
是.NET框架提供的一个轻量级、高性能的HTTP通信基础设施。下面是一个使用HttpClient
进行网络请求和数据交换的基本示例:
首先,你需要创建一个HttpClient
的实例(注意,HttpClient
实例应该被重用而不是为每个请求都创建一个新的实例,因为它内部使用了连接池来优化性能):
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.Net.Http.Headers;
class Program
{
static readonly HttpClient client = new HttpClient(); // 可以作为静态字段或作为类的属性重用
static async Task Main(string[] args)
{
// 示例:发送GET请求
await SendGetRequestAsync("http://example.com/api/data");
// 示例:发送POST请求并包含JSON数据
var content = new StringContent("{\"key\":\"value\"}", Encoding.UTF8, "application/json");
await SendPostRequestAsync("http://example.com/api/data", content);
}
static async Task SendGetRequestAsync(string uri)
{
try
{
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功码
string responseBody = await response.Content.ReadAsStringAsync();
// 在这里处理responseBody,比如解析为JSON对象等
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
static async Task SendPostRequestAsync(string uri, HttpContent content)
{
try
{
// 设置请求头(如果需要的话)
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功码
string responseBody = await response.Content.ReadAsStringAsync();
// 在这里处理responseBody,比如解析为JSON对象等
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
在上面的示例中,我们展示了如何使用HttpClient
发送GET和POST请求。对于GET请求,我们只需要调用GetAsync
方法并传入URL。对于POST请求,我们需要创建一个HttpContent
实例(在这里使用StringContent
来表示JSON数据),并将其传递给PostAsync
方法。
此外,我们使用了HttpResponseMessage
来检查响应的状态码和读取响应内容。在处理完响应后,应该始终关闭或释放资源,但由于HttpClient
和HttpResponseMessage
都实现了IDisposable
接口,因此在await
表达式完成后,它们会自动被垃圾回收器清理。
请注意,当处理JSON数据时,你可能需要使用如Newtonsoft.Json
(现在称为Json.NET
)或System.Text.Json
(.NET Core 3.0及以上版本中的新API)这样的库来序列化和反序列化JSON对象。
PATCH 请求
PATCH请求与POST请求类似,只是HTTP方法不同。
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
string url = "http://example.com/api/data/1";
var content = new StringContent("{\"keyToPatch\":\"newValue\"}", Encoding.UTF8, "application/json");
string response = await SendPatchRequestAsync(url, content);
Console.WriteLine(response);
}
static async Task<string> SendPatchRequestAsync(string url, HttpContent content)
{
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), url);
request.Content = content;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
PUT 请求
PUT请求通常用于更新整个资源。
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
string url = "http://example.com/api/data/1";
var content = new StringContent("{\"key1\":\"value1\",\"key2\":\"value2\"}", Encoding.UTF8, "application/json");
string response = await SendPutRequestAsync(url, content);
Console.WriteLine(response);
}
static async Task<string> SendPutRequestAsync(string url, HttpContent content)
{
HttpResponseMessage response = await client.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
DELETE 请求
对于DELETE请求,由于通常不需要发送请求体,因此我们可以直接使用HttpClient
的DeleteAsync
方法。下面是一个发送DELETE请求的示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
string url = "http://example.com/api/data/1";
await SendDeleteRequestAsync(url);
Console.WriteLine("Deletion successful.");
}
static async Task SendDeleteRequestAsync(string url)
{
HttpResponseMessage response = await client.DeleteAsync(url);
response.EnsureSuccessStatusCode();
// DELETE请求通常没有响应体,所以这里不需要读取内容
}
}
在这个例子中,SendDeleteRequestAsync
方法发送一个DELETE请求到指定的URL,并检查响应状态码以确保请求成功。由于DELETE请求通常没有响应体,所以我们不需要调用ReadAsStringAsync
来读取响应内容。
确保在发送请求时处理可能出现的异常,例如网络问题或服务器错误。你可以使用try-catch块来捕获并处理这些异常。
另外,如果你需要为请求添加额外的头信息或设置超时等选项,可以使用HttpClient
的其他方法和属性。例如,你可以使用DefaultRequestHeaders
属性来设置默认的请求头,或者使用Timeout
属性来设置请求的超时时间。
最后,请注意在使用HttpClient
时,最好将其实例化为一个静态的或长生命周期的对象,而不是在每次请求时都创建一个新的实例。这是因为创建HttpClient
实例可能会消耗相当多的资源,并且频繁的创建和销毁实例可能会导致性能问题。