。net httpclient的工具类
时间: 2024-06-09 08:10:20 浏览: 104
下面是一个简单的 .NET HttpClient 工具类的示例:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpClientHelper
{
private readonly HttpClient _httpClient;
public HttpClientHelper(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetAsync(string url)
{
HttpResponseMessage response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
public async Task<string> PostAsync(string url, HttpContent content)
{
HttpResponseMessage response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
```
使用示例:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
HttpClient httpClient = new HttpClient();
HttpClientHelper httpClientHelper = new HttpClientHelper(httpClient);
string response = await httpClientHelper.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
Console.WriteLine(response);
var content = new StringContent("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}");
response = await httpClientHelper.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
Console.WriteLine(response);
}
}
```
以上示例演示了如何使用 HttpClient 发送 GET 和 POST 请求并处理响应。注意,在实际应用程序中,您可能需要添加更多的错误处理和日志记录等功能。
阅读全文