GKMLT通讯工具箱(WPF MVVM) - 05-WebAPI通讯
一、概述
WebAPI通讯模块实现了基于HTTP/HTTPS协议的RESTful API客户端功能,支持GET、POST等多种HTTP方法,提供JSON数据序列化/反序列化、Bearer Token认证、表单提交等功能。
二、通讯报文原理
2.1 HTTP协议基础
WebAPI通讯基于HTTP/HTTPS协议,采用请求-响应模式:
客户端 → HTTP请求 → 服务器 服务器 → HTTP响应 → 客户端2.2 HTTP请求报文结构
POST /api/resource HTTP/1.1 Host: example.com Content-Type: application/json Authorization: Bearer eyJhbGciOiJIUzI1NiIs... Content-Length: 123 {"key":"value","data":123}请求报文组成:
- 请求行:方法(POST/GET)、URL路径、HTTP版本
- 请求头:Content-Type、Authorization等
- 请求体:JSON数据、表单数据等
2.3 HTTP响应报文结构
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 456 {"status":"success","result":{"data":456}}响应报文组成:
- 状态行:HTTP版本、状态码(200/401/500等)、状态描述
- 响应头:Content-Type、Content-Length等
- 响应体:JSON数据、错误信息等
2.4 JSON数据格式
请求JSON示例:
{"userName":"admin","password":"123456","deviceCode":"DEVICE001"}响应JSON示例:
{"code":200,"message":"success","data":{"token":"eyJhbGciOiJIUzI1NiIs...","expireTime":"2026-12-31T23:59:59"}}2.5 Bearer Token认证流程
1. 客户端发送登录请求(用户名+密码) 2. 服务器验证并返回Token 3. 客户端保存Token 4. 后续请求携带Token: Authorization: Bearer {token} 5. 服务器验证Token后返回数据2.6 OAuth2表单提交
使用application/x-www-form-urlencoded格式:
POST /oauth/token HTTP/1.1 Content-Type: application/x-www-form-urlencoded grant_type=password&username=admin&password=123456&client_id=myapp三、调用的库和方法
3.1 核心库
RestSharp库
- 版本:通过NuGet包管理
- 作用:简化HTTP客户端操作
- 命名空间:
RestSharp
主要类:
RestClient:HTTP客户端,负责发送请求RestRequest:HTTP请求封装IRestResponse:HTTP响应接口Method:HTTP方法枚举(GET/POST/PUT/DELETE)
Newtonsoft.Json库
- 版本:JSON.NET
- 作用:JSON序列化/反序列化
- 命名空间:
Newtonsoft.Json
主要方法:
JsonConvert.SerializeObject():对象→JSON字符串JsonConvert.DeserializeObject():JSON字符串→对象
3.2 核心类:WebApiHelper
3.2.1 HttpPost 方法
功能:发送JSON格式POST请求
方法签名:
publicstaticIRestResponseHttpPost<T>(stringurl,Tbody)参数说明:
url:请求的API地址body:请求体对象(泛型,会被序列化为JSON)
实现代码:
publicstaticIRestResponseHttpPost<T>(stringurl,Tbody){// 创建HTTP客户端RestClientclient=newRestClient(url);client.Timeout=5000;// 创建请求RestRequestrequest=newRestRequest(Method.POST);request.AddHeader("Content-Type","application/json");request.AddJsonBody(body,"application/json");// 生成请求JSON(用于日志)stringrequestJson=JsonConvert.SerializeObject(body,Formatting.Indented);// 执行请求IRestResponseresponse=client.Execute(request);// 触发JSON回调事件RaiseJsonDataEvent(requestJson,response.Content);returnresponse;}调用示例:
varrequestData=new{userName="admin",password="123456"};varresponse=WebApiHelper.HttpPost("https://api.example.com/login",requestData);3.2.2 HttpPostBearerToken 方法
功能:发送带Bearer Token的POST请求
方法签名:
publicstaticIRestResponseHttpPostBearerToken<T>(stringurl,stringtoken,Tbody)参数说明:
url:请求的API地址token:Bearer Token字符串body:请求体对象
实现代码:
publicstaticIRestResponseHttpPostBearerToken<T>(stringurl,stringtoken,Tbody){RestClientclient=newRestClient(url);client.Timeout=5000;RestRequestrequest=newRestRequest(Method.POST);request.AddHeader("Content-Type","application/json");request.AddHeader("Authorization",$"Bearer{token}");request.AddJsonBody(body,"application/json");stringrequestJson=JsonConvert.SerializeObject(body,Formatting.Indented);IRestResponseresponse=client.Execute(request);RaiseJsonDataEvent(requestJson,response.Content);returnresponse;}调用示例:
varrequestData=new{deviceId="DEVICE001",timestamp=DateTime.Now.ToString()};varresponse=WebApiHelper.HttpPostBearerToken("https://api.example.com/api/data","eyJhbGciOiJIUzI1NiIs...",requestData);3.2.3 HttpPost (表单提交) 方法
功能:发送表单格式POST请求(OAuth2等场景)
方法签名:
publicstaticIRestResponseHttpPost(stringurl,Dictionary<string,string>para)参数说明:
url:请求的API地址para:表单参数字典
实现代码:
publicstaticIRestResponseHttpPost(stringurl,Dictionary<string,string>para){RestClientclient=newRestClient(url);client.Timeout=5000;RestRequestrequest=newRestRequest(Method.POST);request.AddHeader("Content-Type","application/x-www-form-urlencoded");// 构建表单数据字符串StringBuilderformData=newStringBuilder();foreach(stringkeyinpara.Keys){if(formData.Length>0){formData.Append("&");}formData.Append($"{Uri.EscapeDataString(key)}={Uri.EscapeDataString(para[key])}");}request.AddParameter("application/x-www-form-urlencoded",formData.ToString(),ParameterType.RequestBody);// 生成请求JSON(用于日志)stringrequestJson=JsonConvert.SerializeObject(para,Formatting.Indented);IRestResponseresponse=client.Execute(request);RaiseJsonDataEvent(requestJson,response.Content);returnresponse;}调用示例:
varformData=newDictionary<string,string>{{"grant_type","password"},{"username","admin"},{"password","123456"},{"client_id","myapp"}};varresponse=WebApiHelper.HttpPost("https://api.example.com/oauth/token",formData);3.2.4 HttpGet 方法
功能:发送GET请求
方法签名:
publicstaticIRestResponseHttpGet<T>(stringurl)参数说明:
url:请求的API地址(可包含查询参数)
实现代码:
publicstaticIRestResponseHttpGet<T>(stringurl){RestClientclient=newRestClient(url);client.Timeout=5000;RestRequestrequest=newRestRequest(Method.GET);returnclient.Execute(request);}调用示例:
varresponse=WebApiHelper.HttpGet<object>("https://api.example.com/api/users?page=1&size=10");3.2.5 FormatJson 方法
功能:格式化JSON字符串(美化输出)
方法签名:
publicstaticstringFormatJson(stringjson)实现代码:
publicstaticstringFormatJson(stringjson){try{objectobj=JsonConvert.DeserializeObject(json);returnJsonConvert.SerializeObject(obj,Formatting.Indented);}catch{returnjson;}}3.3 事件机制
OnJsonDataReceived 事件
功能:当收到HTTP响应时触发,用于UI显示请求/响应数据
事件定义:
publicstaticeventAction<string,string>OnJsonDataReceived;事件参数:
string requestJson:请求JSON字符串string responseJson:响应JSON字符串
触发位置:
- 所有HTTP方法执行后都会触发此事件
使用示例:
// 在ViewModel中订阅事件WebApiHelper.OnJsonDataReceived+=(request,response)=>{// 更新UI显示请求和响应RequestJson=WebApiHelper.FormatJson(request);ResponseJson=WebApiHelper.FormatJson(response);};四、数据流程
4.1 完整的API调用流程
用户操作 ↓ ViewModel调用WebApiHelper方法 ↓ 创建RestClient和RestRequest ↓ 设置请求头(Content-Type、Authorization等) ↓ 序列化请求数据为JSON ↓ 发送HTTP请求 ↓ 接收HTTP响应 ↓ 触发OnJsonDataReceived事件 ↓ UI更新显示请求/响应数据4.2 Bearer Token认证流程
1. 获取Token HttpPost(loginUrl, loginData) → Token 2. 保存Token 存储到ViewModel或配置文件 3. 使用Token访问API HttpPostBearerToken(apiUrl, token, data) → Data 4. Token过期处理 捕获401错误 → 重新获取Token → 重试请求五、错误处理
5.1 常见HTTP状态码
| 状态码 | 含义 | 处理方式 |
|---|---|---|
| 200 | 成功 | 正常处理响应数据 |
| 400 | 请求错误 | 检查请求参数格式 |
| 401 | 未授权 | 重新登录获取Token |
| 403 | 禁止访问 | 检查权限配置 |
| 404 | 资源不存在 | 检查API URL |
| 500 | 服务器错误 | 联系API提供方 |
5.2 异常处理示例
try{varresponse=WebApiHelper.HttpPost(url,data);if(response.StatusCode==System.Net.HttpStatusCode.OK){// 成功处理varresult=JsonConvert.DeserializeObject<ResponseModel>(response.Content);}elseif(response.StatusCode==System.Net.HttpStatusCode.Unauthorized){// 401未授权,重新登录ShowErrorMessage("Token已过期,请重新登录");}else{// 其他错误ShowErrorMessage($"请求失败:{response.StatusCode}");}}catch(Exceptionex){// 网络异常或JSON解析错误ShowErrorMessage($"请求异常:{ex.Message}");}六、性能优化
6.1 超时设置
client.Timeout=5000;// 5秒超时6.2 连接池复用
建议创建单例RestClient实例,避免频繁创建/销毁。
6.3 异步调用
对于耗时API调用,使用异步方法避免阻塞UI线程:
awaitTask.Run(()=>{varresponse=WebApiHelper.HttpPost(url,data);});七、安全性
7.1 HTTPS通信
生产环境必须使用HTTPS加密传输。
7.2 Token存储
- 不要在日志中输出完整Token
- 建议使用安全存储(如Windows Credential Manager)
7.3 敏感数据加密
密码等敏感数据在传输前应加密处理。
八、总结
WebAPI通讯模块提供了完整的HTTP客户端功能:
- 多种HTTP方法:支持GET、POST等常用方法
- 认证支持:Bearer Token、OAuth2表单认证
- JSON处理:自动序列化/反序列化
- 事件机制:请求/响应数据实时通知
- 错误处理:完善的异常捕获和状态码处理
该模块可广泛应用于对接各类RESTful API服务,如云平台、IoT平台、AI服务等场景。
