码迷,mamicode.com
首页 > Web开发 > 详细

居于HttpWebRequest的HTTP GET/POST请求

时间:2019-10-11 18:42:37      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:owa   auto   add   https   sum   redirect   foreach   false   ror   

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;
        }
    }
}

 

居于HttpWebRequest的HTTP GET/POST请求

标签:owa   auto   add   https   sum   redirect   foreach   false   ror   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!