123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- 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
- {
- /// <summary>
- ///
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="url"></param>
- /// <param name="dto">dto对象</param>
- /// <returns></returns>
- public static AjaxResult<T> PostRequest<T>(string url, object dto)
- {
- 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(20);
- var message = new HttpRequestMessage(HttpMethod.Post, url);
- message.Content = content;
- var response = client.SendAsync(message).Result;
- response.EnsureSuccessStatusCode();
- var result = response.Content.ReadAsStringAsync().Result;
- var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
- return AjaxResult;
- }
- public static string UploadFile(string localFile, string uploadUrl)
- {
- try
- {
- // 添加文件内容到 MultipartFormDataContent
- byte[] fileBytes = File.ReadAllBytes(localFile);
- 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(20);
- var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
- message.Content = content;
- var response = client.SendAsync(message).Result;
- response.EnsureSuccessStatusCode();
- var result = response.Content.ReadAsStringAsync().Result;
- 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}失败!");
- }
- }
- }
- }
|