首页 > 编程语言 >C# HTTP请求 get post

C# HTTP请求 get post

时间:2024-05-31 16:57:53浏览次数:20  
标签:HTTP string C# request result reader post null response

C# HTTP请求 get post

    public class HttpRequestHelper
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        /// <summary>
        /// 向指定URL发送GET方法的请求
        /// </summary>
        /// <param name="url">发送请求的URL</param>
        /// <param name="param">请求参数,请求参数应该是 name1=value1&name2=value2 的形式。</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static string SendGet(string url, string param)
        {
            string result = String.Empty;
            StreamReader reader = null;
            try
            {
                string urlNameString = url + "?" + param;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
                #region 没有证书
                //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                request = (HttpWebRequest)HttpWebRequest.Create(url);

                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //设置协议类型前设置协议版本req.ProtocolVersion = HttpVersion.Version11;
                //这里设置了协议类型。
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 1000;
                ServicePointManager.Expect100Continue = false;
                #endregion
                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = (HttpWebResponse)ex.Response;
                }
                Stream responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                result = reader.ReadToEnd();

                reader.Close();
                responseStream.Close();
                response.Close();
                reader = null;
                responseStream = null;
                response = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常:" + ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 向指定URL发送GET方法的请求
        /// </summary>
        /// <param name="url">发送请求的URL</param>
        /// <param name="param">请求参数,请求参数应该是 name1=value1&name2=value2 的形式。</param>
        /// <param name="encoding">设置响应信息的编码格式,如utf-8</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static string SendGet(string url, string param, string encoding)
        {
            string result = String.Empty;
            StreamReader reader = null;
            try
            {
                string urlNameString = url + "?" + param;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString);
                request.Method = "GET";
                request.ContentType = "text/html;charset=" + encoding;
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
                result = reader.ReadToEnd();

                reader.Close();
                responseStream.Close();
                response.Close();
                reader = null;
                responseStream = null;
                response = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常:" + ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 向指定 URL 发送POST方法的请求
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="jsonData">请求参数,请求参数应该是Json格式字符串的形式。</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static string SendPost(string url, string jsonData)
        {
            string result = String.Empty;
            try
            {
                CookieContainer cookie = new CookieContainer();

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Headers.Add("x-requested-with", "XMLHttpRequest");
                request.ServicePoint.Expect100Continue = false;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
                request.ContentLength = Encoding.UTF8.GetByteCount(jsonData);
                request.CookieContainer = cookie;
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {

                    writer.Write(jsonData);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cookie.GetCookies(response.ResponseUri);
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        result = reader.ReadToEnd();

                        reader.Close();
                    }
                    responseStream.Close();
                }
                response.Close();
                response = null;
                request = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常:" + ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 向指定 URL 发送POST方法的请求
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="jsonData">请求参数,请求参数应该是Json格式字符串的形式。</param>
        /// <param name="encoding">设置响应信息的编码格式,如utf-8</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static string SendPost(string url, string jsonData, string encoding)
        {
            string result = String.Empty;
            try
            {
                CookieContainer cookie = new CookieContainer();

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Headers.Add("x-requested-with", "XMLHttpRequest");
                request.ServicePoint.Expect100Continue = false;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
                request.ContentLength = Encoding.UTF8.GetByteCount(jsonData);
                request.CookieContainer = cookie;
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding(encoding)))
                {

                    writer.Write(jsonData);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cookie.GetCookies(response.ResponseUri);
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)))
                    {
                        result = reader.ReadToEnd();

                        reader.Close();
                    }
                    responseStream.Close();
                }
                response.Close();
                response = null;
                request = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常:" + ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 上传媒体文件
        /// </summary>
        /// <param name="url">上传媒体文件的微信公众平台接口地址</param>
        /// <param name="file">要上传的媒体文件对象</param>
        /// <returns>返回上传的响应结果,详情参看微信公众平台开发者接口文档</returns>
        public static string UploadPost(string url, string file)
        {
            string result = String.Empty;
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                byte[] responseArray = client.UploadFile(url, "POST", file);
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                Console.WriteLine("上传result:" + result);
            }
            catch (Exception ex)
            {
                result = "Error:" + ex.Message;
                Console.WriteLine("发送GET请求出现异常:" + ex.Message);
            }
            finally
            {
                Console.WriteLine("上传MediaId:" + result);
            }
            return result;
        }

        public static bool DownloadFile(string url, string param, string outFileName)
        {
            bool result = false;
            FileStream fs = null;
            try
            {
                string urlNameString = url + "?" + param;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                fs = new FileStream(outFileName, FileMode.Create);
                int bufferSize = 2048;
                byte[] data = new byte[bufferSize];
                int length = 0;
                while ((length = responseStream.Read(data, 0, bufferSize)) > 0)
                {
                    fs.Write(data, 0, length);
                }
                fs.Close();
                responseStream.Close();
                response.Close();
                fs = null;
                responseStream = null;
                response = null;

                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("下载媒体文件时出现异常:" + ex.Message);

            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return result;
        }
View Code

 

标签:HTTP,string,C#,request,result,reader,post,null,response
From: https://www.cnblogs.com/love201314/p/18224838

相关文章

  • Spire.Office 9.5.0 for .NET
    Spire.Officefor.NETisacombinationofEnterprise-LevelOffice.NETAPIofferedbyE-iceblue.ItincludesSpire.Doc,Spire.XLS,Spire.Spreadsheet,Spire.Presentation,Spire.PDF,Spire.DataExport,Spire.OfficeViewer,Spire.PDFViewer,Spire.DocViewer,Sp......
  • Uscrapper:一款功能强大的网络资源爬取工具
    关于UscrapperUscrapper是一款功能强大的网络资源爬取工具,该工具可以帮助广大研究人员从各种网络资源中轻松高效地提取出有价值的数据,并且提供了稳定、友好且易于使用的UI界面,是安全研究人员和网络分析人员的强有力工具。Uscrapper最大程度地释放了开源情报资源的力量,该工具......
  • docker-compose 安装 yapi
    docker-compose安装yapidocker-compose.yamlversion:'3'services:yapi-web:image:liuqingzheng/yapi:latestcontainer_name:yapi-webports:-3000:3000environment:[email protected]_ADMI......
  • 安防综合管理系统EasyCVR平台对接GA/T1400视图库:基于XML的消息体格式
    GA/T1400标准的应用范围广泛,涵盖了公安系统的视频图像信息应用系统,如警务综合平台、治安防控系统、交通管理系统等。在视频监控系统中,GA/T1400公安视图库的对接是实现视频图像信息传输、处理和管理的重要环节。以视频汇聚EasyCVR视频监控资源管理平台为例,该平台已经与GA/T14......
  • C. Tea Tasting
    题目链接:https://codeforces.com/problemset/problem/1795/Corhttps://www.luogu.com.cn/problem/CF1795C总思路:利用数组记录a[N],b[N]分别记录每杯茶的量,每个人喝的量,然后每个人喝的量进行前缀和,再二分查找,利用divx和mod来确定每个人喝的量:divx是喝了几整杯;mod是额外的......
  • linux 离线安装docker
    docker-ce下载地址很多情况下我们不能对docker进行在线安装,这时可以参照本篇博客尝试进行离线安装docker-ce1.下载对应版本的安装包2.解压安装包tar-zxvfdocker-XXX.tgz3.将解压的文件复制到指定位置cp./docker/*/usr/bin4.配置docker服务的文件如下cd/etc/syste......
  • 基于对比稀疏扰动技术的时间序列解释框架 ContraLSP
    开篇近日,由阿里云计算平台大数据基础工程技术团队主导,与南京大学、宾夕法尼亚州立大学、清华大学等高校合作,解释时间序列预测模型的论文《ExplainingTimeSeriesviaContrastiveandLocallySparsePerturbations》被机器学习领域顶会ICLR2024接收。该论文提出了一种创新的基......
  • springboot+seata+nacos+dubbo搭建分布式事务
    一、环境springboot:2.3.1.RELEASEdubbo:2.7.13seata:1.8nacos:zookeeper:3.7.1java11mysql8依赖:以下版本经测试无依赖冲突#父工程springboot版本<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent......
  • pytest + yaml 框架 - 70.Pycharm 设置 yaml 格式用例模板,高效写用例
    前言初学者对yaml格式不太熟悉,自己写yaml用例的时候,总是格式对不齐,或者有些关键字会忘记。于是我们可以在pycharm上设置用例模块,通过快捷方式调用出对应的模块,达到高效写用例的目的。pycharm设置用例模板File-SettingsLiveTemplates-python点+号选择LiveTempl......
  • Fiddler设置抓取https包
    fiddler下载地址:Fiddler4(telerik.com)安装成功: 配置可抓取HTTPS:导入证书后即可抓取:  ......