首页 > 编程语言 >C# HTTP帮助类

C# HTTP帮助类

时间:2024-04-02 09:44:06浏览次数:18  
标签:帮助 HTTP string C# HttpRequestType url new response

HTTP请求类型枚举

namespace Demo
{
    /// <summary>
    /// HTTP请求类型
    /// </summary>
    public enum HttpRequestType
    {
        /// <summary>
        /// GET请求
        /// </summary>
        GET,
        /// <summary>
        /// POST请求
        /// </summary>
        POST,
        /// <summary>
        /// PUT请求
        /// </summary>
        PUT,
        /// <summary>
        /// DELETE请求
        /// </summary>
        DELETE,
    }
}
View Code

HTTP帮助类

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Demo
{
    /// <summary>
    /// HTTP帮助类
    /// </summary>
    public static class HttpHelper
    {
        /// <summary>
        /// HTTP请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jwt"></param>
        /// <param name="requestType"></param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <param name="mediaType"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public static async Task<string> HttpRequestAsync(string url, string jwt = null, HttpRequestType? requestType = HttpRequestType.GET, string data = null, Encoding encoding = null, string mediaType = "application/json")
        {
            // 忽略SSL验证
            HttpClientHandler handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            // HTTP客户端
            using HttpClient client = new HttpClient();
            // 设置JWT身份验证头
            if (jwt != null)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
            }
            // 构造请求内容
            StringContent content = new StringContent(string.Empty);
            if (data != null)
            {
                content = new StringContent(JsonConvert.SerializeObject(data), encoding ??= Encoding.UTF8, mediaType);
            }
            // 发起请求
            Logger.Info(String.Format("http request,  url: {0}, type: {1}, body: {2}", url, requestType, data));
            HttpResponseMessage response = null;
            // 判断请求类型
            switch (requestType)
            {
                case HttpRequestType.GET:
                    response = await client.GetAsync(url);
                    break;
                case HttpRequestType.POST:
                    response = await client.PostAsync(url, content);
                    break;
                case HttpRequestType.PUT:
                    response = await client.PutAsync(url, content);
                    break;
                case HttpRequestType.DELETE:
                    response = await client.DeleteAsync(url);
                    break;
            }
            // 检查响应是否成功
            if (response?.IsSuccessStatusCode == true)
            {
                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                Logger.Info(String.Format("http response, url: {0}, type: {1}, body: {2}", url, requestType, responseBody));
                return responseBody;
            }
            else
            {
                throw new Exception(String.Format("HTTP请求失败,状态码:{0}", response?.StatusCode));
            }
        }
        /// <summary>
        /// HTTP请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jwt"></param>
        /// <param name="requestType"></param>
        /// <param name="data"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> HttpRequestAsync(string url, string jwt = null, HttpRequestType? requestType = HttpRequestType.GET, string data = null, CancellationToken cancellationToken = default)
        {
            try
            {
                // 忽略SSL验证
                HttpClientHandler handler = new HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
                // HTTP客户端
                using HttpClient client = new HttpClient(handler);
                // 设置JWT身份验证头
                if (!string.IsNullOrEmpty(jwt))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
                }
                // 构造请求内容
                StringContent content = new StringContent(string.Empty);
                if (!string.IsNullOrEmpty(data))
                {
                    content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                }
                // 发起请求
                Logger.Info(String.Format("http request, url: {0}, type: {1}, body: {2}", url, requestType, data));
                HttpResponseMessage response = null;
                // 判断请求类型
                switch (requestType)
                {
                    case HttpRequestType.GET:
                        response = await client.GetAsync(url, cancellationToken);
                        break;
                    case HttpRequestType.POST:
                        response = await client.PostAsync(url, content, cancellationToken);
                        break;
                    case HttpRequestType.PUT:
                        response = await client.PutAsync(url, content, cancellationToken);
                        break;
                    case HttpRequestType.DELETE:
                        response = await client.DeleteAsync(url, cancellationToken);
                        break;
                }
                // 检查响应是否成功
                if (response?.IsSuccessStatusCode == true)
                {
                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Logger.Info(String.Format("http response, url: {0}, type: {1}, body: {2}", url, requestType, responseBody));
                    return responseBody;
                }
                else
                {
                    throw new Exception(String.Format("HTTP请求失败,状态码:{0}", (int)response?.StatusCode));
                }
            }
            catch (OperationCanceledException ex)
            {
                throw new Exception(String.Format("HTTP请求失败,请求已终止:{0}", ex.Message));
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
View Code

 

翻译

搜索

复制

标签:帮助,HTTP,string,C#,HttpRequestType,url,new,response
From: https://www.cnblogs.com/smartnn/p/18109903

相关文章

  • 【leetcode】链表篇刷题 --
    //删除指定value节点classSolution{public:ListNode*removeElements(ListNode*head,intval){//单独处理headwhile(head!=NULL&&head->val==val){ListNode*temp=head;head=head->next;......
  • 【Docker】搭建便捷的Docker容器管理工具 - dockerCopilot
    【Docker】搭建便捷的Docker容器管理工具-dockerCopilot前言本教程基于绿联的NAS设备DX4600Pro的docker功能进行搭建。前面有介绍过OneKey,而dockerCopilot便是OneKey的升级版,作者对其进行了重新命名,并且对界和功能都进行了全面的优化。目前通过绿联自带的Docker管理器......
  • 【SQL Server】2. 将数据导入导出到Excel表格当中
    最开始,博主介绍一下自己的环境:SQLSever2008R2SQLSever大致都差不多1.通过自带软件的方式首先找到下载SQLSever中提供的导入导出工具如果开始界面没有找到自己下载的路径C:\ProgramFiles\MicrosoftSQLServer\100\DTS\Binn下的DTSWizard.exe文件导出1.1......
  • 大数据之 MapReduce 相关的 Java API 应用
    注意:本文基于前两篇教程Linux系统CentOS7上搭建HadoopHDFS集群详细步骤YARN集群和MapReduce原理及应用MapReduce是ApacheHadoop项目中的一种编程模型,用于大规模数据集的并行处理。在Hadoop中,MapReduce使用JavaAPI来编写Map和Reduce函数。API简......
  • C#/.NET/.NET Core优秀项目和框架2024年3月简报
    前言公众号每月定期推广和分享的C#/.NET/.NETCore优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架......
  • 【wu-acw-client 使用】案例
    wu-acw-client使用项目介绍,使用acw-client,创建对应Java项目的增删改查(ORM:LazyORM、mybatis),项目模块架构:mvc、feign、ddd演示项目环境:idea、mac、mysql、jdk17springboot3.0.7稳定版本1.2.3-JDK17第一步通过idea创建一个项目选择通过springInitializr创建......
  • 2024年数字IC秋招-禾赛-IC验证工程师-笔试题
    文章目录前言一、不定项选择题1、同步时序电路的状态只在统一的时钟脉冲控制下才同时变化一次,如果时钟脉冲没有到来,即使输入信号发生变化,电路的状态仍不改变2、reg[255:0]mem[31:0];该声明定义了一个位宽为32bits,深度为256的memory3、Verilog语句中,下列哪些语......
  • 深度干货|谈谈阿里云AnalyticDB Spark如何构建低成本数据湖分析
    文/李少锋阿里云瑶池旗下的云原生数据仓库AnalyticDBMySQL版是基于湖仓一体架构打造的实时湖仓。本文将分享AnalyticDBMySQLSpark助力构建低成本数据湖分析的最佳实践。全文目录:AnalyticDBMySQL介绍AnalyticDBMySQLServerlessSpark核心优化基于AnalyticDBMySQL......
  • golang语言系列:Scrum、Kanban等敏捷管理策略
    云原生学习路线导航页(持续更新中)本文是golang语言系列文章,主要对编程通用技能Scrum、Kanban等敏捷管理策略进行学习1.什么是敏捷开发敏捷是一个描述软件开发方法的术语,它强调增量交付、团队协作、持续规划和持续学习。2001年,敏捷宣言提出:个体和交互胜过流程和......
  • 【浙江工业大学主办,嘉宾阵容强大 | IEEE出版,往届均已检索!!】第四届IEEE电子,电路和信息
    第四届IEEE电子,电路和信息工程国际学术会议(ECIE2024)将于2024年5月24日至26日于杭州举行。ECIE2024致力于为电子,电路和信息工程等相关领域的学者,工程师和从业人员提供一个分享最新研究成果的平台。会议征稿主题主要包括但不限于单片机技术,电工技术,电力系统通信,信息与通信工程,......