对HttpClient的封装

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

services.AddHttpClient<HttpProvider>();

services.AddHttpClient<HttpProvider>(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

results matching ""

    No results matching ""