HttpHelper是对HttpClient的封装,可自动处理RsCode中WebApi返回的数据格式,也可重写你想要的格式

使用步骤:

1. 注册服务
services.AddHttpClient<HttpHelper>();

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
HttpHelper httpHelper;
public Order(HttpHelper _httpHelper)
{ 
    httpHelper=_httpHelper;
}
3. HttpHelper使用实例

3.1 发送post请求的例子

//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请求

await httpHelper.GetAsync<T>(url,token);
await httpHelper.GetAsync<T>(url);
await httpHelper.GetPageAsync<T>(url); //获取PetaPoco.Page<T>类型的数据

3.3 获取地址栏参参数值 例:

var id=httpHelper.GetUrlParamValue("http://rscode.cn?id=222 ","id");  // id=222   

捕获AppException异常

try
{
   await httpHelper.GetAsync<object>(url);
}
catch(AppException e)
{
}
catch(Exception ex)
{
}

常见错误:

向服务器发送数据后,返回空字符串 修改发送的数据:

var httpContent = new StringContent(JsonSerializer.Serialize(obj));

正确数据格式:

var httpContent = new StringContent(JsonSerializer.Serialize(obj),System.Text.Encoding.UTF8,"application/json");