🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
##更新 2022.03.23 NET6修改为HttpClient为底层方法 ## 原生 HttpClient 微软自带的HttpClient更适用于异步单进程场景. NetCore 2.1 推出的IHttpClientFactory虽然解决了并发的问题,但只在Windows下使用正常,在Linux环境下多并发依旧会导致进程堵塞. ## IHttp ~~使用 HttpWebRequest / HttpWebResponse 底层封装实现, 性能高运行稳定方便使用.~~ ## 请求三方网站 GET 请求 ``` public IActionResult TestRequest() { //注意client 使用完成后需要 Dispose, 所以推荐使用using using var httpClient = IHttp.Instance.CreateRequest("http://www.baidu.com"); var result = httpClient.Get(); return new StringActionResult { Code = "0000", Data = result.GetResult() }; } ``` POST 请求 ``` public IActionResult TestRequest() { using var httpClient = IHttp.Instance.CreateRequest("http://www.baidu.com"); httpClient.AddHeaders("Referer", "https://www.baidu.com/"); httpClient.AddHeaders("Content-Type", "application/x-www-form-urlencoded"); httpClient.SetCookies("cookies"); var resp = httpClient.Post("a=1&b=2"); var cookies = resp.GetCookies(); //新增 Result 属性写法 同 resp.GetResult() return new StringActionResult { Code = "0000", Data = resp.Result }; } ``` ## 下载文件 ``` public IActionResult TestDownloadFile() { var downloadUrl = "http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4"; using var request = IHttp.Instance.CreateRequest(downloadUrl); var response = request.Get(); var savePath = Path.Combine(Environment.CurrentDirectory, "download"); var filePath = Path.Combine(savePath, "test.mp4"); var result = response.DownloadFile(filePath, 0); return new DefaultActionResult { Code = "0000", Data = result }; } ```