C#-Http协议通讯(五)-HttpClient
1.C#-Socket_TCP、Socket_UDP、WebSocket、WebService、WCF、WebAPI、MQTT的基础使用2.C#-TCP协议通讯(一)-TCPClientHelper_Net53.C#-TCP协议通讯(二)-处理TCP粘包与拆包4.C#-UDP协议通讯(一)-UDPClientHelper_Net55.C#-UDP协议通讯(二)-优化丢包问题6.C#-Http协议通讯(一)-目录7.C#-Http协议通讯(三)-HttpWebRequest
8.C#-Http协议通讯(五)-HttpClient
9.C#-WebService协议通讯_Net510.C#-WCF协议通讯_Net511.C#-WebSocket协议通讯_Net512.MQTT学习笔记(C#)-MQTTnet13.C#-网络通讯框架(一)-HPSocket14.C#-网络通讯框架(二)-DotNetty_Net715.C#-网络通讯框架(三)-SignalR(SignalRCore版)_Net7/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述: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; }
}
}
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/17003873.html
合集:
C#-网络通信
分类:
C#+通讯_网络通信
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2021-12-25 WPF-控件_圆角属性