zoukankan      html  css  js  c++  java
  • .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}");
                }
            }
    
           
        }
    }
  • 相关阅读:
    扁平化职能管理三部曲
    [转载]持续交付和DevOps的前世今生
    敏捷项目管理工具-百度效率云
    敏捷项目管理:基础知识与应用实务
    第8章 “敏捷+”创新创业模式
    第7章 "敏捷+"项目管理
    第6章 迭代循环与项目结束
    第5章 发布循环
    第4章 立项与项目启动
    Windows 2003 + IIS6.0 相关 401.1 或 401.2 等问题解决
  • 原文地址:https://www.cnblogs.com/Mzg121584668/p/15565932.html
Copyright © 2011-2022 走看看