居于HttpWebRequest的HTTP GET/POST请求

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace UnitTes
{
    public class HttpHandler
    {
        /// <summary>
        ///  HTTP 带请求头的 Post Json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonStr"></param>
        /// <param name="headers"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static System.Net.HttpWebResponse CreatePostJsonHeaderResponse(string url, string jsonStr, IDictionary<string, string> headers=null, int timeout=10000, Encoding requestEncoding=null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            if (null == headers || headers.Count == 0)
            {
                return CreatePostJsonResponse(url, jsonStr, timeout, requestEncoding);
            }

            HttpWebRequest request = null;
            HttpWebResponse SendSMSResponse = null;
            Stream dataStream = null;
            CookieContainer cookieContainer = new CookieContainer();
            try
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.KeepAlive = false;
                request.ServicePoint.ConnectionLimit = 300;
                request.AllowAutoRedirect = true;
                request.Timeout = timeout;
                request.ReadWriteTimeout = 10000;
                request.ContentType = "application/json";
                //request.Accept = "application/xml";
                request.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode("openstack"));
                string strContent = jsonStr;
                byte[] bytes = requestEncoding.GetBytes(strContent);
                request.Proxy = null;
                request.CookieContainer = cookieContainer;

                foreach (var pair in headers)
                {
                    request.Headers[pair.Key] = pair.Value;
                }

                using (dataStream = request.GetRequestStream())
                {
                    dataStream.Write(bytes, 0, bytes.Length);
                }
                SendSMSResponse = (HttpWebResponse)request.GetResponse();
                return SendSMSResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///  HTTP Basic 验证 Post Json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="userpw"></param>
        /// <param name="jsonStr"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostJsonBasicResponse(string username, string userpw, string url, string jsonStr, int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            HttpWebRequest request = null;
            HttpWebResponse SendSMSResponse = null;
            Stream dataStream = null;
            CookieContainer cookieContainer = new CookieContainer();
            try
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.KeepAlive = false;
                request.ServicePoint.ConnectionLimit = 300;
                request.AllowAutoRedirect = true;
                request.Timeout = timeout;
                request.ReadWriteTimeout = 10000;
                request.ContentType = "application/json";
                string strContent = jsonStr;
                byte[] bytes = requestEncoding.GetBytes(strContent);
                request.Proxy = null;
                request.CookieContainer = cookieContainer;
                NetworkCredential netCredential = new NetworkCredential(username, userpw);
                Uri uri = new Uri(url);
                ICredentials credentials = netCredential.GetCredential(uri, "Basic");
                if (netCredential != null)
                {
                    byte[] credentialBuffer = requestEncoding.GetBytes(
                         netCredential.UserName + ":" +
                         netCredential.Password);
                    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
                }
                else
                {
                    throw new ApplicationException("No network credentials");
                }

                using (dataStream = request.GetRequestStream())
                {
                    dataStream.Write(bytes, 0, bytes.Length);
                }
                SendSMSResponse = (HttpWebResponse)request.GetResponse();
                return SendSMSResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// HTTP post json/body
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonStr"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostJsonResponse(string url, string jsonStr, int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            HttpWebRequest request = null;
            try
            {
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }

                request.Method = "POST";
                request.KeepAlive = false;
                request.ServicePoint.ConnectionLimit = 300;
                request.AllowAutoRedirect = true;
                request.Timeout = timeout;
                request.ReadWriteTimeout = 10000;
                request.ContentType = "application/json";
                //request.Accept = "application/xml";
                request.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode("openstack"));
                string strContent = jsonStr;
                byte[] bytes = requestEncoding.GetBytes(strContent);
                request.Proxy = null;
                using (var dataStream = request.GetRequestStream())
                {
                    dataStream.Write(bytes, 0, bytes.Length);
                }
                var SendSMSResponse = (HttpWebResponse)request.GetResponse();
                return SendSMSResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// HTTP post from
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            HttpWebRequest request = null;

            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = timeout;

            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// HTTP 带请求头的 Get from
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="headers"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreateGetHttpHeaderResponse(string url, IDictionary<string, string> parameters, IDictionary<string, string> headers , int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            if (null == headers || headers.Count == 0)
            {
                return CreateGetHttpResponse(url, parameters, timeout, requestEncoding);
            }

            StringBuilder buffer = new StringBuilder();
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("?{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }

            string requestUrl = url + buffer.ToString();

            HttpWebRequest request = null;
            if (requestUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
            }
            request.Method = "GET";

            foreach (var pair in headers)
            {
                request.Headers[pair.Key] = pair.Value;
            }
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        ///HTTP GET from
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreateGetHttpResponse(string url, IDictionary<string, string> parameters, int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            StringBuilder buffer = new StringBuilder();
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("?{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }

            string requestUrl = url + buffer.ToString();

            HttpWebRequest request = null;
            if (requestUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
            }
            request.Method = "GET";

            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// HTTP Basic 验证 Get form
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="networkCredentials"></param>
        /// <param name="timeout"></param>
        /// <param name="requestEncoding"></param>
        /// <returns></returns>
        public static HttpWebResponse CreateGetHttpBasicResponse(string url, IDictionary<string, string> parameters, NetworkCredential networkCredentials, int timeout = 10000, Encoding requestEncoding = null)
        {
            requestEncoding = requestEncoding == null ? Encoding.UTF8 : requestEncoding;
            StringBuilder buffer = new StringBuilder();
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("?{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }

            string requestUrl = url + buffer.ToString();

            HttpWebRequest request = null;
            if (requestUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
            }

            if (networkCredentials != null)
            {
                byte[] credentialBuffer = new UTF8Encoding().GetBytes(
                     networkCredentials.UserName + ":" +
                     networkCredentials.Password);
                request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
            }
            else
            {
                throw new ApplicationException("No network credentials");
            }

            request.Method = "GET";

            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();

            }
        }

        /// <summary>
        /// 验证证书
        /// </summary>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            /*if (errors == SslPolicyErrors.None)
                return true;
            return false;*/
            return true;
        }
    }
}

原文地址:https://www.cnblogs.com/zengtianli/p/11655554.html

时间: 2024-10-02 11:21:04

居于HttpWebRequest的HTTP GET/POST请求的相关文章

C# winform端 通过HttpWebRequest进行post和get请求,数据格式为json,后台java端接收,其中有关传输特殊字符(\t,\r,&#39;,\n,n)等处理

问题:C# winform端 通过HttpWebRequest进行post和get请求,数据格式为json,后台java端接收,其中有关传输特殊字符(\t,\r,',\n,n)等处理 原因:传输时,会把空格,\t,\r,',n 等特殊字符序列化为一些%20....等字符 解决: 所以再传输前先在.net端进行System.Web.HttpUtility.UrlEncode(参数)编码,java后台接收端进行URLDecoder.decode(request.getAttribute(参数).to

C#中调用HttpWebRequest类中Get/Post请求无故失效的诡异问题

先附代码 /// <summary> /// 客户端Http(GET) /// </summary> /// <param name="strUrl">请求路径</param> /// <returns>response字符串</returns> public string HttpGet(string strUrl) { // string strEncodeUrl = HttpUtility.UrlEncode

C# 利用HttpWebRequest进行HTTPS的post请求的示例

最近一个推送信息的目标接口从http格式换成https格式,原来的请求无法正常发送,所以修改了发送请求的方法.标红的代码是新加了,改了之后就可以正常访问(不检测证书的) public static string PostData3(string posturl, string postData, Encoding encoding) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWeb

C#后台HttpWebRequest模拟跨域Ajax请求,注册Windows服务到服务器上

项目需求,暂且叫A.B公司吧.我们公司需要从A公司哪里读取机器上的数据,放到我们数据库中.然后再将数据库中存的数据,提供一个接口,B公司来调用,大概这个意思. 好了,言归正传.这个是之前做好的界面,用户需要手动点击“开始”,然后写了个定时器,不停的来回调用 部分源码(5秒调用后台处理) 1 function refreshCount() { 2 if (prj.is_port_state_1 == false) { 3 var grid_down = query_panel.grid_down;

【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传文件请求报文内容封装 3.asp.net(c#)使用HttpWebRequest携带请求参数模拟上传文件封装源码下载 一.Http协议上传文件(以图片为例)请求报文体内容格式 首先,我们来看下通过浏览器上传文件的请求报文内容格式,这里以本人自己写的实例为例,如下图.除了能上传图片(即:头像字段),还

httpWebRequest请求错误,基础连接已经关闭: 连接被意外关闭

win10下,C# 用httpWebRequest 执行post请求出现"请求错误,基础连接已经关闭: 连接被意外关闭",经测试设置 //Post请求方式 System.Net.HttpWebRequest request;            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);            //Post请求方式            request.Method = "P

后端向服务器发送客户端请求--HttpWebRequest

HttpWebRequest类与HttpRequest类的区别 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所有信息. HttpWebRequest用于客户端,拼接请求的HTTP报文并发送等.它封装了几乎HTTP请求报文里需要用到的东西,以致于能够能够发送任意的HTTP请求并获得服务器响应(Response)信息.采集信息常用到这个类 1 private ApiResultModel GetDataByProductIdInApi(int P

C#利用 HttpWebRequest 类发送post请求,出现“套接字(协议/网络地址/端口)只允许使用一次”问题

声明:问题虽然已经被解决,但是并没有明白具体原理,欢迎大佬补充. 最近网站出现一个问题,在C#里面使用  HttpWebRequest 类去发送post请求,偶尔 会出现 “套接字(协议/网络地址/端口)只允许使用一次” 的异常,很明显应该是端口被占用. 原因排查: 1.网上说最多就是其他程序占用端口:因为已经上线,并且有时候可以正常运行,因此排除其他程序占用端口的可能,而且我网站用的就是80端口. 2.第二个可能原因就是接口性能较差,占用较长处理时间:我 给post的目标接口(因为接口也是本身

Windows Phone 十五、HttpWebRequest

Windows 运行时中支持网络资源访问的对象:HttpWebRequest 对象 发送 GET/POST 请求,HttpHelper 封装,超时控制. HttpClient 对象 发送 GET/POST 请求,请求进度监控. 两种常用请求方式:GET 请求 主要是从服务器请求数据 可以传递有限(1024字节)数据 POST 请求 主要是往服务器发送数据,传递数据大小没有限制. 也可以接收服务端数据,但大多数是请求结果标识. HttpWebRequest 1 <Grid> 2 <WebV