在工程中创建一个Http消息类 HttpMessage,并在这个类中分别实现Http的Get、Post、Push和Delete方法。
异步任务Get
public async Task<string> GetAsync<T>(string path)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Your Uri");
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return content;
}
throw new Exception($"Error getting data from API: {response.StatusCode}");
}
异步任务Post
public async Task<T> PostAsync<T>(string path, object content)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Your Uri");
string jsonContent = JsonConvert.SerializeObject(content);
StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(path, stringContent);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result);
}
throw new HttpRequestException($"Error posting data to API: {response.StatusCode}");
}
异步任务Put
public async Task<HttpResponseMessage> PutAsync(string path, object content)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Your Uri");
string jsonContent = JsonConvert.SerializeObject(content);
StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync(path, stringContent);
return response;
}
异步任务Delete
public async Task<HttpResponseMessage> DeleteAsync(string path)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Your Uri");
HttpResponseMessage response = await client.DeleteAsync(path);
return response;
}
响应类型
// 响应类型
public class MyResponseType
{
public string Message { get; set; }
// 其他属性...
}
根据以方法,可以通过C#实现网络的Http消息收发机制。