IHttp 封装是因早期版本 HttpClient 存在问题而做的,但是随着版本的迭代底层的 HttpWebRequest 被启用后改成了 HttpClient 关键字: HttpClient, Http, Net [[toc]]
实例化对象
默认 HttpClient 配置
内置的单例做了 HttpClientHandler 配置限制
new HttpClientHandler
{
AllowAutoRedirect = true,
UseCookies = false,
ClientCertificateOptions = ClientCertificateOption.Automatic,
ServerCertificateCustomValidationCallback = (message, cert, cetChain, policyErrors) => true
}
GET 请求
public IActionResult GetTest()
{
//注意client 使用完成后需要 Dispose, 所以推荐使用using
using var req = IHttp.New.Request("http://www.baidu.com");
var resp = req.Get();
return new StringActionResult { Code = "0000", Data = resp.Result };
}
POST 请求
public IActionResult GetTest()
{
using var req = IHttp.New.Request("http://www.baidu.com");
var resp = req.Post("a=1&b=2");
return new StringActionResult { Code = "0000", Data = resp.Result };
}
设置请求头
HttpClient 设置 Content-Type 是让 IHttp 一直存在的一个很重要原因
AddHeaders
public IActionResult GetTest()
{
using var req = IHttp.New.Request("http://www.baidu.com");
req.AddHeaders("Referer", "https://www.baidu.com/");
req.AddHeaders("Content-Type", "application/x-www-form-urlencoded");
var resp = req.Post("a=1&b=2");
return new StringActionResult { Code = "0000", Data = resp.Result };
}
::: tip 设置 Content-Type 只用一个通用函数,是不是简单到会担心它不生效 :grin: :::
Cookies
虽然默认的 HttpClientHandler 关闭了使用 Cookie, 但是通过 SetCookies 和 GetCookies 就可以轻松在使用时带上 Cookies ,最重要的是更可控!
using var request = IHttp.New.Request("http://www.baidu.com");
request.SetCookies("cookies");
var resp = request.Post("a=1&b=2");
var cookies = resp.GetCookies();
下载文件
DownloadFile 可以控制文件的保存目录以及下载速度,并且返回一个字典数据
/// <param name="path">下载地址</param>
/// <param name="speed">默认下载速度500K/S</param>
public IActionResult GetDownloadFile()
{
var downloadUrl = "http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4";
using var request = IHttp.New.Request(downloadUrl);
var savePath = Path.Combine(Environment.CurrentDirectory, "download");
var filePath = Path.Combine(savePath, "test.mp4");
var response = request.DownloadFile(filePath, 0);
return new DefaultActionResult { Code = "0000", Data = response };
}
::: tip DownloadFile 返回的字典数据,包含参数如下:
|参数名|说明| |-|-| |Time|下载所需时间| |Speed|下载平均速度| |File|文件路径| :::