123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 |
- 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>
- /// <typeparam name="T"></typeparam>
- /// <param name="url"></param>
- /// <param name="dto"></param>
- /// <param name="timeoutSeconds"></param>
- /// <param name="token"></param>
- /// <returns></returns>
- public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, int timeoutSeconds = 30, CancellationToken token = default)
- {
- var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
- var handler = new HttpClientHandler() { UseCookies = false };
- HttpClient client = new HttpClient(handler);
- client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
- var message = new HttpRequestMessage(HttpMethod.Post, url);
- message.Content = content;
- var response = await client.SendAsync(message, token);
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="url"></param>
- /// <param name="dto"></param>
- /// <param name="token"></param>
- /// <param name="timeoutSeconds"></param>
- /// <returns></returns>
- public static async Task<AjaxResult> PostRequestAsync(string url, object dto, int timeoutSeconds = 30, CancellationToken token = default)
- {
- var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
- var handler = new HttpClientHandler() { UseCookies = false };
- HttpClient client = new HttpClient(handler);
- client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
- var message = new HttpRequestMessage(HttpMethod.Post, url);
- message.Content = content;
- var response = await client.SendAsync(message, token);
- 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, int timeoutSeconds = 30)
- {
- var handler = new HttpClientHandler() { UseCookies = false };
- HttpClient client = new HttpClient(handler);
- client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
- var response = await client.GetAsync(url);
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="baseUrl"></param>
- /// <param name="remoteFileName"></param>
- /// <param name="localFile"></param>
- /// <param name="timeoutSeconds"></param>
- /// <returns></returns>
- public static async Task<bool> DownloadFileAsync(string baseUrl, string remoteFileName, string localFile, int timeoutSeconds = 30)
- {
- if (!baseUrl.EndsWith("/"))
- baseUrl += "/";
- var server = new Uri(baseUrl + $"wwwroot/{remoteFileName}");
- var httpClient = new HttpClient();
- httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
- var responseMessage = await httpClient.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="uploadUrl"></param>
- /// <param name="timeoutSeconds"></param>
- /// <param name="token"></param>
- /// <returns></returns>
- public static async Task<string> UploadFileAsync(string localFile, string uploadUrl, int timeoutSeconds = 30, CancellationToken token = default)
- {
- 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 handler = new HttpClientHandler() { UseCookies = false };
- HttpClient client = new HttpClient(handler);
- client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
- var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
- message.Content = content;
- var response = await client.SendAsync(message, token);
- 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)
- {
- throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
- }
- catch
- {
- throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!");
- }
- }
- }
- /// <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;
- }
|