gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
c# 我要写一个通用类 api的 httpclient
- User
c# 我要写一个通用类 api的 httpclient
- Assistant
以下是一个通用类 API 的 C# HttpClient 的示例代码:
using System; using System.Net.Http; using System.Threading.Tasks; public class ApiHttpClient { private readonly HttpClient _httpClient; public ApiHttpClient(string baseUrl) { _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) }; } public async Task<string> GetAsync(string apiUrl) { HttpResponseMessage response = await _httpClient.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { throw new Exception($"Api request failed with status code: {response.StatusCode}"); } } public async Task<string> PostAsync<T>(string apiUrl, T data) { string dataJson = System.Text.Json.JsonSerializer.Serialize(data); HttpResponseMessage response = await _httpClient.PostAsync(apiUrl, new StringContent(dataJson)); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { throw new Exception($"Api request failed with status code: {response.StatusCode}"); } } public async Task<string> PutAsync<T>(string apiUrl, T data) { string dataJson = System.Text.Json.JsonSerializer.Serialize(data); HttpResponseMessage response = await _httpClient.PutAsync(apiUrl, new StringContent(dataJson)); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { throw new Exception($"Api request failed with status code: {response.StatusCode}"); } } public async Task DeleteAsync(string apiUrl) { HttpResponseMessage response = await _httpClient.DeleteAsync(apiUrl); if (!response.IsSuccessStatusCode) { throw new Exception($"Api request failed with status code: {response.StatusCode}"); } } }使用方法示例:
var apiClient = new ApiHttpClient("https://api.example.com"); string response = await apiClient.GetAsync("/users");这个示例代码实现了 GET、POST、PUT 和 DELETE 方法,可以自行根据需要扩展其他 HTTP 方法。在使用的时候,只需要创建一个 ApiHttpClient 实例并调用相应的方法即可。注意在使用 HttpClient 时要确保正确地处理异常和释放资源。