12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- 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.Tasks;
- using XdCxRhDw.Dto;
- namespace XdCxRhDW.Core
- {
- public class HttpHelper
- {
- public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto,int timeoutSeconds=30)
- {
- 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);
- response.EnsureSuccessStatusCode();
- var result = response.Content.ReadAsStringAsync().Result;
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- /// <summary>
- /// 上传文件,wav文件会自动去掉44字节头
- /// </summary>
- /// <param name="localFile"></param>
- /// <param name="uploadUrl"></param>
- /// <param name="timeoutSeconds"></param>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public static async Task<string> UploadFileAsync(string localFile, string uploadUrl, int timeoutSeconds = 30)
- {
- 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);
- response.EnsureSuccessStatusCode();
- var result = await response.Content.ReadAsStringAsync();
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<FileUploadResDto>>(result);
- if (AjaxResult.code == 200)
- {
- return AjaxResult.data.FileName;
- }
- else
- {
- throw new Exception(AjaxResult.msg);
- }
- }
- catch
- {
- throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!");
- }
- }
- }
- }
|