灞呬簬HttpWebRequest鐨凥TTP GET/POST璇锋眰

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了灞呬簬HttpWebRequest鐨凥TTP GET/POST璇锋眰相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/owa' title='owa'>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))
                {
                    //瀵规湇鍔$璇佷功杩涜鏈夋晥鎬ф牎楠岋紙闈炵涓夋柟鏉冨▉鏈烘瀯棰佸彂鐨勮瘉涔︼紝濡傝嚜宸辩敓鎴愮殑锛屼笉杩涜楠岃瘉锛岃繖閲岃繑鍥瀟rue锛?/span>
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;    //http鐗堟湰锛岄粯璁ゆ槸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))
            {
                //瀵规湇鍔$璇佷功杩涜鏈夋晥鎬ф牎楠岋紙闈炵涓夋柟鏉冨▉鏈烘瀯棰佸彂鐨勮瘉涔︼紝濡傝嚜宸辩敓鎴愮殑锛屼笉杩涜楠岃瘉锛岃繖閲岃繑鍥瀟rue锛?/span>
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http鐗堟湰锛岄粯璁ゆ槸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))
            {
                //瀵规湇鍔$璇佷功杩涜鏈夋晥鎬ф牎楠岋紙闈炵涓夋柟鏉冨▉鏈烘瀯棰佸彂鐨勮瘉涔︼紝濡傝嚜宸辩敓鎴愮殑锛屼笉杩涜楠岃瘉锛岃繖閲岃繑鍥瀟rue锛?/span>
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http鐗堟湰锛岄粯璁ゆ槸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))
            {
                //瀵规湇鍔$璇佷功杩涜鏈夋晥鎬ф牎楠岋紙闈炵涓夋柟鏉冨▉鏈烘瀯棰佸彂鐨勮瘉涔︼紝濡傝嚜宸辩敓鎴愮殑锛屼笉杩涜楠岃瘉锛岃繖閲岃繑鍥瀟rue锛?/span>
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http鐗堟湰锛岄粯璁ゆ槸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))
            {
                //瀵规湇鍔$璇佷功杩涜鏈夋晥鎬ф牎楠岋紙闈炵涓夋柟鏉冨▉鏈烘瀯棰佸彂鐨勮瘉涔︼紝濡傝嚜宸辩敓鎴愮殑锛屼笉杩涜楠岃瘉锛岃繖閲岃繑鍥瀟rue锛?/span>
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http鐗堟湰锛岄粯璁ゆ槸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鐨凥TTP GET/POST璇锋眰的主要内容,如果未能解决你的问题,请参考以下文章

銆屾煡缂鸿ˉ婕忋€嶅珐鍥轰綘鐨凥TTP鐭ヨ瘑浣撶郴

html+css-姘村钩灞呬腑-涓嶅畾娆惧潡鐘跺厓绱犳柟娉曪紙浜岋級

鏈煡瀹介珮鐨刣iv姘村钩鍨傜洿灞呬腑

vb.net如何使用HttpWebRequest模拟登陆带验证码的网站

TTP233D-SB6,TTP233D-RB6 优势代理通泰全系列TTP233D-SB6原装

原装TTP中华区一级代理TTP233D-RB6 DFN-6 进口原装芯片 提供PDF参考设计方案