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}");
                }
            }
    
           
        }
    }
  • 相关阅读:
    D11 列表 list 元祖 字典dict
    D10 基本数据类型(各种职业的技能分析) 主要为 int 和 str
    Python D9 学习
    面向对象方法传参实现数组求和,求平均值
    用带参数的方法给空数组放元素,寻找数组里面的值是否存在。
    两种方法把类和对象写在同一个文件内
    创建一个管理员对象,输入正确用户名和密码,可以修改密码(类和对象分为两个文件,区别于放在一个文件内)
    创建一个游客对象,输入信息判断游客年龄是否免费游览
    建立一个学生对象,输出学生信息
    把输入的数字转为数组,拿出其中的最小值
  • 原文地址:https://www.cnblogs.com/Mzg121584668/p/15565932.html
Copyright © 2011-2022 走看看