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

使用步骤: 1.Startup.cs中注册服务

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;
}

发送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);

发送GET请求

await httpHelper.GetAsync<object>(url,token);
await httpHelper.GetAsync<object>(url);
await httpHelper.GetItemsAsync<object>(url);

捕获AppException异常

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

获取地址栏参参数值 例:

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

常见错误:

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

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

正确数据格式:

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

results matching ""

    No results matching ""