123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Security.Policy;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- /// <summary>
- /// http调用帮助类
- /// </summary>
- public class HttpHelper
- {
- /// <summary>
- /// 文件删除模型
- /// </summary>
- class FileDeleteDto
- {
- /// <summary>
- /// 要删除的服务器上的文件名称
- /// </summary>
- public List<string> Files { get; set; }
- }
- static HttpHelper()
- {
- client = new HttpClient(new HttpClientHandler()
- {
- UseCookies = false,
- UseDefaultCredentials = false,
- UseProxy = false,
- AllowAutoRedirect = false,
- });
- client.Timeout = TimeSpan.FromSeconds(60);
- //client.MaxResponseContentBufferSize //该值默认为2GB
- downLoadClient = new HttpClient(new HttpClientHandler()
- {
- UseCookies = false,
- UseDefaultCredentials = false,
- UseProxy = false,
- AllowAutoRedirect = false,
- });
- downLoadClient.Timeout = TimeSpan.FromSeconds(180);
- }
- private static HttpClient client;
- private static HttpClient downLoadClient;
- public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, CancellationToken token = default)
- {
- var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
- var message = new HttpRequestMessage(HttpMethod.Post, url);
- message.Content = content;
- var response = await client.SendAsync(message, token);
- message.Dispose();//http1.1没啥用,http2有用
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- public static async Task<AjaxResult> PostRequestAsync(string url, object dto, CancellationToken token = default)
- {
- var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
- var message = new HttpRequestMessage(HttpMethod.Post, url);
- message.Content = content;
- var response = await client.SendAsync(message, token);
- message.Dispose();//http1.1没啥用,http2有用
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult>(result);
- return AjaxResult;
- }
- public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url)
- {
- var response = await client.GetAsync(url);
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- public static async Task<bool> DownloadFileAsync(string baseUrl, string remoteFileName, string localFile)
- {
- baseUrl = baseUrl.Replace("/api", "");
- if (!baseUrl.EndsWith("/"))
- baseUrl += "/";
- var server = new Uri(baseUrl + $"wwwroot/{remoteFileName}");
- var responseMessage = await downLoadClient.GetAsync(server);
- if (responseMessage.IsSuccessStatusCode)
- {
- using (var fs = File.Create(localFile))
- {
- // 获取结果,并转成 stream 保存到本地。
- var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
- streamFromService.CopyTo(fs);
- }
- return true;
- }
- else
- return false;
- }
- public static async Task<bool> DownloadFileAsync(string url, string localFile)
- {
- var server = new Uri(url);
- var responseMessage = await downLoadClient.GetAsync(server);
- if (responseMessage.IsSuccessStatusCode)
- {
- using (var fs = File.Create(localFile))
- {
- // 获取结果,并转成 stream 保存到本地。
- var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
- streamFromService.CopyTo(fs);
- }
- return true;
- }
- else
- return false;
- }
- /// <summary>
- /// 上传文件,wav文件会自动去掉44字节头
- /// </summary>
- /// <param name="localFile"></param>
- /// <param name="baseUrl"></param>
- /// <param name="token"></param>
- /// <returns></returns>
- public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
- {
- string uploadUrl = baseUrl;
- if (baseUrl.EndsWith("/"))
- uploadUrl += "File/UploadFileAsync";
- else
- uploadUrl += "/File/UploadFileAsync";
- try
- {
- // 添加文件内容到 MultipartFormDataContent
- FileInfo info = new FileInfo(localFile);
- bool isWav = info.Extension.ToLower() == ".wav";
- byte[] fileBytes = File.ReadAllBytes(localFile);
- if (isWav)
- {
- fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
- }
- MultipartFormDataContent content = new MultipartFormDataContent();
- ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
- content.Add(fileContent, "file", Path.GetFileName(localFile));
- var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
- message.Content = content;
- var response = await downLoadClient.SendAsync(message, token);
- message.Dispose();
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(result);
- if (AjaxResult.code == 200)
- {
- return AjaxResult.data;
- }
- else
- {
- throw new Exception(AjaxResult.msg);
- }
- }
- catch (TaskCanceledException)
- {
- if (token != default && token.IsCancellationRequested)
- throw new TaskCanceledException();
- else
- throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
- }
- catch (Exception ex)
- {
- throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
- }
- }
- /// <summary>
- /// 删除文件
- /// </summary>
- /// <param name="files">要删除的文件</param>
- /// <param name="baseUrl">baseUrl</param>
- /// <returns></returns>
- public static async Task<int> DeleteFileAsync(string baseUrl, params string[] files)
- {
- FileDeleteDto dto = new FileDeleteDto()
- {
- Files = files.ToList()
- };
- var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
- var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
- message.Content = content;
- var response = await client.SendAsync(message);
- message.Dispose();
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
- return AjaxResult.data;
- }
- }
- /// <summary>
- /// Http接口返回泛型对象
- /// </summary>
- public class AjaxResult<T>
- {
- /// <summary>
- /// 返回对象
- /// </summary>
- public T data { get; set; }
- /// <summary>
- /// 返回消息
- /// </summary>
- public string msg { get; set; } = "ok";
- /// <summary>
- /// 状态码.成功=200,失败=0
- /// </summary>
- public int code { get; set; } = 200;
- }
- /// <summary>
- /// Http接口返回对象
- /// </summary>
- public class AjaxResult
- {
- /// <summary>
- /// 返回对象
- /// </summary>
- public object data { get; set; }
- /// <summary>
- /// 返回消息
- /// </summary>
- public string msg { get; set; } = "ok";
- /// <summary>
- /// 状态码.成功=200,失败=0
- /// </summary>
- public int code { get; set; } = 200;
- }
|