.NET Core Http請求(GET、POST、上傳文件並攜帶參數)


using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;namespace Yanglao.Common.Helper
{
    public class HttpHelper
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public HttpHelper()
        {
            this._httpClientFactory = ServiceProviderHelper.ServiceProvider.GetRequiredService<IHttpClientFactory>();
        }

        public async Task<string> GetAsync(string url, Dictionary<string, string> headers = null, int timeoutSecond = 0)
        {
            var client = _httpClientFactory.CreateClient();
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            if (timeoutSecond != 0)
                client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new HttpException($"HttpCode:{response.StatusCode},Message:{response.ReasonPhrase}");
            }
        }

        public async Task<string> PostAsync(string url, string requestString, HttpContentType contentType = HttpContentType.json, Dictionary<string, string> headers = null, int timeoutSecond = 0)
        {
            var client = _httpClientFactory.CreateClient();
            var requestContent = new StringContent(requestString, Encoding.UTF8, contentType.GetDescription());
            if (headers != null)
            {
                foreach (var head in headers)
                {
                    requestContent.Headers.Add(head.Key, head.Value);
                }
            }
            if (timeoutSecond != 0)
                client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
            var response = await client.PostAsync(url, requestContent);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new HttpException($"HttpCode:{response.StatusCode},Message:{response.ReasonPhrase}");
            }
        }

        /// <summary>
        /// 上傳文件方法
        /// </summary>
        /// <param name="parameter">上傳文件請求參數</param>
        public async Task<string> PostFileAsync(UploadParameterDto parameter, Dictionary<string, string> headers = null, int timeoutSecond = 0)
        {
            var client = _httpClientFactory.CreateClient();
            var content = new MultipartFormDataContent();
            var fileSteamConten = new StreamContent(parameter.UploadStream);
            fileSteamConten.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            content.Add(fileSteamConten, parameter.FileNameKey,parameter.FileNameValue);
            if (parameter.PostParameters != null && parameter.PostParameters.Count > 0)
            {
                foreach (KeyValuePair<string, string> keyValuePair in parameter.PostParameters)
                {
                    content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                }
            }

            if(headers != null)
            {
                foreach (var head in headers)
                {
                    content.Headers.Add(head.Key, head.Value);
                }
            }
            if (timeoutSecond != 0)
                client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
            //parameter.Url = "http://localhost:9329/api/External/LanidIdentityAuth";
            var response = await client.PostAsync(new Uri(parameter.Url), content);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new HttpException($"HttpCode:{response.StatusCode},Message:{response.ReasonPhrase}");
            }
        }

        public async Task<string> PutAsync(string url, string requestString, HttpContentType contentType = HttpContentType.json, Dictionary<string, string> headers = null, int timeoutSecond = 0)
        {
            var client = _httpClientFactory.CreateClient();
            var requestContent = new StringContent(requestString, Encoding.UTF8, contentType.GetDescription());
            if (headers != null)
            {
                foreach (var head in headers)
                {
                    requestContent.Headers.Add(head.Key, head.Value);
                }
            }
            if (timeoutSecond != 0)
                client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
            var response = await client.PutAsync(url, requestContent);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new HttpException($"HttpCode:{response.StatusCode},Message:{response.ReasonPhrase}");
            }
        }


        public async Task<string> DeleteAsync(string url, Dictionary<string, string> headers = null, int timeoutSecond = 0)
        {
            var client = _httpClientFactory.CreateClient();
            var request = new HttpRequestMessage(HttpMethod.Delete, url);
            if (headers != null)
            {
                foreach (var head in headers)
                {
                    request.Headers.Add(head.Key, head.Value);
                }
            }
            if (timeoutSecond != 0)
                client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                throw new HttpException($"HttpCode:{response.StatusCode},Message:{response.ReasonPhrase}");
            }
        }

       
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM