HttpHelper是对HttpClient的封装,可自动处理RsCode中WebApi返回的数据格式
使用步骤:
1. 注册服务
csharp
services.AddHttpClient<HttpHelper>();
或
csharp
services.AddHttpClient<HttpHelper>(c =>
{
c.BaseAddress = new Uri("https://api.rscode.cn/api/");
c.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 Edg/81.0.416.68");
});
2. 构造注入HttpHelper
csharp
HttpHelper httpHelper;
public Order(HttpHelper _httpHelper)
{
httpHelper=_httpHelper;
}
3. HttpHelper使用实例
3.1 发送post请求的例子
csharp
//1.实例化请求数据
var obj=new CreateOrderDto();
//2.实例化httpcontent json格式 向header 添加accesstoken
var httpContent = new StringContent(JsonSerializer.Serialize(obj),System.Text.Encoding.UTF8,"application/json");
//3.发送POST请求
var order=await httpHelper.PostAsync<OrderInfoDto>("https://api.rscode.cn/api/order", httpContent,token);
3.2 发送GET请求
csharp
await httpHelper.GetAsync<T>(url,token);
await httpHelper.GetAsync<T>(url);
await httpHelper.GetPageAsync<T>(url); //获取PetaPoco.Page<T>类型的数据
3.3 获取地址栏参参数值
例:
csharp
var id=httpHelper.GetUrlParamValue("http://rscode.cn?id=222 ","id"); // id=222
捕获AppException异常
csharp
try
{
await httpHelper.GetAsync<object>(url);
}
catch(AppException e)
{
}
catch(Exception ex)
{
}
常见问题:
如何处理非 WebApi返回的数据格式? 将第三个参数设置为false,例如:
csharp
var order=await httpHelper.PostAsync<OrderInfoDto>("https://api.rscode.cn/api/order", httpContent,token,false);
向服务器发送数据后,返回空字符串 修改发送的数据:
csharp
//这是错误的代码
var httpContent = new StringContent(JsonSerializer.Serialize(obj));
正确数据格式:
csharp
var httpContent = new StringContent(JsonSerializer.Serialize(obj),System.Text.Encoding.UTF8,"application/json");