IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> C#发送http与https请求公共类 -> 正文阅读

[网络协议]C#发送http与https请求公共类

兼容http与https请求的公共类新鲜出炉(小白上路,老司机绕道)…

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace OneCardEduWF.zbscxy.common
{
    class HttpUtils
    {
        /// <summary>
        /// 以json字符串的形式返回服务器内容,默认使用utf-8编码
        /// </summary>
        /// <param name="redata">返回的数据</param>
        /// <param name="serviceAddress">服务器器地址</param>
        /// <param name="reqToken">token</param>
        /// <returns></returns>
        public static bool sendHttpGet(out string redata, string serviceAddress, string reqToken)
        {
            try
            {
                if (serviceAddress.Length <= 0)
                {
                    redata = null;
                    return false;
                }
                // Encoding encode = Encoding.GetEncoding(encodeType);
                // HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);

                //添加https兼容处理
                HttpWebRequest request = null;
                if (serviceAddress.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    request = WebRequest.Create(serviceAddress) as HttpWebRequest;
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request.ProtocolVersion = HttpVersion.Version11;
                    // 这里设置了协议类型。
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                    request.KeepAlive = false;
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 100;
                    ServicePointManager.Expect100Continue = false;
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                }

                if (null!=reqToken && reqToken.Length>0)
                {
                    request.Headers.Add("Authorization", reqToken);
                }
                request.Method = "GET";
                request.ContentType = "application/json";
                request.Timeout = 300000;
                request.ServicePoint.ConnectionLimit = 50;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string strResponse = string.Empty;

                //读取返回数据流
                if ("gzip".Equals(response.ContentEncoding))
                {
                    using (Stream responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress))
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                else if ("deflate".Equals(response.ContentEncoding))
                {
                    using (Stream responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress))
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                else
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                redata = strResponse;
                return true;
            }
            catch (Exception ex)
            {
                redata = null;
                LogUtils.Error(serviceAddress+"---HttpUtils---sendHttpGet---error:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 以json字符串的形式返回服务器内容,默认使用utf-8编码
        /// </summary>
        /// <param name="redata">返回的数据</param>
        /// <param name="serviceAddress">服务器器地址</param>
        /// <param name="postContent">提交的参数</param>
        /// <returns></returns>
        public static bool sendHttpPost(out string redata, string serviceAddress, string postContent, string reqToken)
        {
            try
            {
                if (serviceAddress.Length <= 0)
                {
                    redata = null;
                    return false;
                }
                // Encoding encode = Encoding.GetEncoding(encodeType);
                // HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);

                //添加https兼容处理
                HttpWebRequest request = null;
                if (serviceAddress.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    request = WebRequest.Create(serviceAddress) as HttpWebRequest;
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request.ProtocolVersion = HttpVersion.Version11;
                    // 这里设置了协议类型。
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                    request.KeepAlive = false;
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 100;
                    ServicePointManager.Expect100Continue = false;
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                }

                if (null != reqToken && reqToken.Length > 0)
                {
                    request.Headers.Add("Authorization", reqToken);
                }
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Timeout = 300000;
                request.ServicePoint.ConnectionLimit = 50;
                string strContent = postContent;
                using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                {
                    dataStream.Write(strContent);
                    dataStream.Close();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string strResponse = string.Empty;

                //读取返回数据流
                if ("gzip".Equals(response.ContentEncoding))
                {
                    using (Stream responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress))
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                else if ("deflate".Equals(response.ContentEncoding))
                {
                    using (Stream responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress))
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                else
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
                            strResponse = streamReader.ReadToEnd().Trim();
                        }
                        else
                        {
                            redata = null;
                            return false;
                        }
                    }
                }
                redata = strResponse;
                return true;
            }
            catch (Exception ex)
            {
                redata = null;
                LogUtils.Error(serviceAddress + "---HttpUtils---sendHttpPost---error:" + ex.Message);
                return false;
            }
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true; //总是接收
        }
    }
}

亲测有效

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-16 19:59:41  更:2021-10-16 19:59:59 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 3:47:11-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码