/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:C#-HttpClient帮助类
*│ 作 者:执笔小白
*│ 版 本:1.0
*│ 创建时间:2022-11-20 15:40:56
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: Util.WebClient
*│ 类 名:HttpClientHelper
*└──────────────────────────────────────────────────────────────┘
*/
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace leap_uav_information_platform_Util.WebClient
{
public class HttpClientHelper
{
/// <summary>
/// Http客户端
/// HttpClient是.NET4.5引入的一个HTTP客户端库
/// HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。
/// 它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。
/// HttpClient有预热机制,第一次进行访问时比较慢,所以不应该用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例
/// </summary>
HttpClient _client;
/// <summary>
/// 传输载体
/// </summary>
JsonSerializerOptions _serializerOptions;
public HttpClientHelper()
{
_client = new HttpClient();
_serializerOptions = new JsonSerializerOptions // 配置从 Web 服务接收并发送到 Web 服务的 JSON 有效负载的格式
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 属性命名策略-驼峰命名法
WriteIndented = true, // 自动缩进
};
}
#region 示例
/// <summary>
/// Get方法示例
/// </summary>
/// <returns></returns>
public async Task<List<TodoItem>> GetDemo_Async()
{
List<TodoItem> Items = new();
string urlStr = "";
Uri uri = new Uri(urlStr);
try
{
HttpResponseMessage response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode) // 调用成功
{
string content = await response.Content.ReadAsStringAsync();
Items = JsonSerializer.Deserialize<List<TodoItem>>(content, _serializerOptions); // 按照指定json格式解析json
}
}
catch (Exception ex)
{
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
return Items;
}
/// <summary>
/// Post方法示例
/// Put方法示例
///
/// 201 (CREATED) – 请求导致在发送响应之前创建新资源。
/// 204(NO CONTENT) – 请求已成功处理,响应有意为空。
/// 400 (BAD REQUEST) – 服务器无法理解请求。
/// 404 (找不到) – 请求的资源不存在于服务器上。
/// 409 (CONFLICT) – 由于服务器上的冲突,无法执行请求
/// </summary>
/// <param name="item"></param>
/// <param name="isNewItem"></param>
/// <returns></returns>
public async Task PostOrPutDome_Async(TodoItem item, bool isNewItem = false)
{
string urlStr = "";
Uri uri = new Uri(urlStr);
try
{
string json = JsonSerializer.Serialize<TodoItem>(item, _serializerOptions);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
if (isNewItem)
response = await _client.PostAsync(uri, content);
else
response = await _client.PutAsync(uri, content);
if (response.IsSuccessStatusCode)
Debug.WriteLine(@"\tTodoItem successfully saved.");
}
catch (Exception ex)
{
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
}
/// <summary>
/// Delete方法示例
///
/// 204 (NO CONTENT) – 请求已成功处理,响应有意为空。
/// 400 (BAD REQUEST) – 服务器无法理解请求。
/// 404 (找不到) – 请求的资源不存在于服务器上。
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task DeleteDome_Async(string id)
{
string urlStr = "";
Uri uri = new Uri(urlStr);
try
{
HttpResponseMessage response = await _client.DeleteAsync(uri);
if (response.IsSuccessStatusCode)
Debug.WriteLine(@"\tTodoItem successfully deleted.");
}
catch (Exception ex)
{
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
}
#endregion 示例
}
/// <summary>
/// 测试类
/// </summary>
public class TodoItem
{
/// <summary>
/// id
/// </summary>
public string ID { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string Notes { get; set; }
/// <summary>
///
/// </summary>
public bool Done { get; set; }
}
}
作者:꧁执笔小白꧂