首页 > 其他分享 >.NET HttpHelper

.NET HttpHelper

时间:2025-01-05 21:33:47浏览次数:7  
标签:contentType string application HttpHelper headers using NET null

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using System.Net.Http;

namespace HttpCore
{
public class HttpAction
{
///


/// 发起POST同步请求
///

///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
// 忽略SSL证书验证
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateValidation);
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null){
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}

    private static bool IgnoreCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        // 这里总是返回true以忽略证书验证
        return true;
    }
    /// <summary>
    /// 发起POST异步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
    /// <param name="headers">填充消息头</param>
    /// <returns></returns>
    public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
    {
        // 忽略SSL证书验证
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateValidation);
        postData = postData ?? "";
        using (HttpClient client = new HttpClient())
        {
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                if (contentType != null)
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = await client.PostAsync(url, httpContent);
                return await response.Content.ReadAsStringAsync();
            }
        }
    }

    /// <summary>
    /// 发起GET同步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="headers"></param>
    /// <param name="contentType"></param>
    /// <returns></returns>
    public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
    {
        // 忽略SSL证书验证
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateValidation);
        using (HttpClient client = new HttpClient())
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

    /// <summary>
    /// 发起GET异步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="headers"></param>
    /// <param name="contentType"></param>
    /// <returns></returns>
    public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
    {
        // 忽略SSL证书验证
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateValidation);
        using (HttpClient client = new HttpClient())
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }
    }

    /// <summary>
    /// 发起POST同步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
    /// <param name="headers">填充消息头</param>
    /// <returns></returns>
    public static T HttpPost<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
    {
        return HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
    }

    /// <summary>
    /// 发起POST异步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
    /// <param name="headers">填充消息头</param>
    /// <returns></returns>
    public static async Task<T> HttpPostAsync<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
    {
        var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
        return res.ToEntity<T>();
    }

    /// <summary>
    /// 发起GET同步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="headers"></param>
    /// <param name="contentType"></param>
    /// <returns></returns>
    public static T HttpGet<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
    {
        return HttpGet(url, contentType, headers).ToEntity<T>();
    }

    /// <summary>
    /// 发起GET异步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="headers"></param>
    /// <param name="contentType"></param>
    /// <returns></returns>
    public static async Task<T> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
    {
        var res = await HttpGetAsync(url, contentType, headers);
        return res.ToEntity<T>();
    }
}
/// <summary>
/// Json扩展方法
/// </summary>
public static class JsonExtends
{
    public static T ToEntity<T>(this string val)
    {
        return JsonConvert.DeserializeObject<T>(val);
    }
    public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
    {
        return JsonConvert.SerializeObject(entity, formatting);
    }
}

}

标签:contentType,string,application,HttpHelper,headers,using,NET,null
From: https://www.cnblogs.com/ff-king/p/18653934

相关文章

  • Eval-Expression.NET:动态执行C#脚本,类似Javascript的Eval函数功能
    我们都知道在JavaScript中,我们可以通过Eval来执行JavaScript字符串代码。下面推荐一个.Net版本的Eval的开源项目。01项目简介Eval-Expression.NET是一个非常强大工具,使得开发人员可以动态编译和执行C#代码和表达式。通过C#反射,还能轻松访问公共和私有方法、字段、属性值......
  • Training Deep Neural Networks with 8-bit Floating Point Numbers
    目录概主要内容WangN.,ChoiJ.,BrandD.,ChenC.andGopalakrishnanK.Trainingdeepneuralnetworkswith8-bitfloatingpointnumbers.NeurIPS,2018.概本文提出了一种8-bit的训练方式.主要内容本文想要实现8-bit的训练,作者认为主要挑战是两个向量的......
  • PEPNet:融合个性化先验信息的多场景多任务网络
    论文链接:https://arxiv.org/pdf/2302.01115背景&动机现在推荐系统大多为多场景多任务,如下图所示,有多个页面,每个页面视为一个场景,如快手的精选、首页、发现页面,每个场景下有多个任务,如点赞、关注、收藏等。如果每个场景、每个任务都训练一个独立的模型,当场景、任务很多的......
  • 【C#/.NET】record介绍
     ​ 目录 什么是record?使用recordrecord解构record原理结论 什么是record?record是.NET5中的一种新特性,可以看作是一种概念上不可变的类。records可以帮助我们在C#中更容易地处理数据,同时提供了重要的功能,如对象相等性、hashcode和解构。与类不同,records具有值......
  • YOLOv11改进策略【Neck】| ArXiv 2023,基于U - Net v2中的的高效特征融合模块:SDI
    一、本文介绍本文聚焦于利用U-Netv2中的SDI模块优化YOLOv11的目标检测网络模型。SDI模块相较于传统模块独具特色,它融合了先进的特征融合思想,借助精心设计的结构,在确保计算资源高效利用的前提下,巧妙地融合不同层级特征的语义信息与细节,实现特征的全方位增强。在应用于YOL......
  • [.NET] 单位转换实践:深入解析 Units.NET
    单位转换实践:深入解析Units.NET摘要在现代软件开发中,准确处理不同单位的转换是一个常见而复杂的需求。无论是处理温度、长度、重量还是其他物理量,都需要可靠的单位转换机制。本文将深入介绍Units.NET库,展示如何在.NET应用中优雅地处理单位转换。基础配置首先,通过NuGet......
  • [ Netty ] 通过Netty聊天业务来加深理解Netty运行以及网络编程.
    引言这几天在学习Netty网络编程的过程当中对Netty的运作原理及流程有一定的了解,通过Netty实现聊天业务来加深对Netty的理解.这里用一张图概括运行流程这里我在Github上面找到一位大神总结的尚硅谷的学习笔记,里面有写Netty的运作原理(但是因为前面一直在讲原理我自己身原因容......
  • 软件缺少netevent.dll文件及错误提示问题
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因为......
  • 软件缺少neth.dll文件及错误提示问题
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因为......
  • 软件缺少netlogon.dll文件及错误提示问题
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因为......