c# HttpHelper类 Http请求通用方法

下面是HttpHelper类

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 HttpHelperNamespace
{
    public static class HttpHelper
    {

        /// 
        /// http/https请求响应
        /// 
        /// 
        /// 地址(要带上http或https)
        /// 请求头
        /// 提交数据
        /// 编码类型 utf-8
        /// application/x-www-form-urlencoded
        /// 
        public static HttpWebResponse HttpRequest(
            string getOrPost,
            string url,
            Dictionary headers,
            Dictionary parameters,
            Encoding dataEncoding,
            string contentType
            )
        {
            var request = CreateRequest(getOrPost, url, headers, parameters, dataEncoding, contentType);

            //如果需要POST数据  
            if (getOrPost == "POST" && !(parameters == null || parameters.Count == 0))
            {
                var data = FormatPostParameters(parameters, dataEncoding, contentType);

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }
            }

            WebResponse Res = null;
            try
            {
                Res = request.GetResponse();
            }
            catch (WebException ex)
            {
                Res = (HttpWebResponse)ex.Response;
            }
            catch (Exception e)
            {
                throw e;
            }

            if (null == Res) {
                return request.GetResponse() as HttpWebResponse;
            }
                
            return (HttpWebResponse)Res;
        }


        /// 
        /// 创建HTTP请求对象
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private static HttpWebRequest CreateRequest(
            string getOrPost
            , string url
            , Dictionary headers
            , Dictionary parameters
            , Encoding paraEncoding
            , string contentType
            )
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            if (parameters != null && parameters.Count > 0 && paraEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }

            HttpWebRequest request = null;
            //判断是否是https  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }

            if (getOrPost == "GET")
            {
                request.Method = "GET";

                if (parameters != null && parameters.Count > 0)
                {
                    url = FormatGetParametersToUrl(url, parameters, paraEncoding);
                }
            }
            else
            {
                request.Method = "POST";
            }

            if (contentType == null)
            {
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            }
            else
            {
                request.ContentType = contentType;
            }

            //POST的数据大于1024字节的时候,如果不设置会分两步
            request.ServicePoint.Expect100Continue = false;
            request.ServicePoint.ConnectionLimit = int.MaxValue;

            if (headers != null)
            {
                FormatRequestHeaders(headers, request);
            }

            return request;
        }


        /// 
        /// 格式化请求头信息
        /// 
        /// 
        /// 
        private static void FormatRequestHeaders(Dictionary headers, HttpWebRequest request)
        {
            foreach (var hd in headers)
            {
                //因为HttpWebRequest中很多标准标头都被封装成只能通过属性设置,添加的话会抛出异常
                switch (hd.Key.ToLower())
                {
                    case "connection":
                        request.KeepAlive = false;
                        break;
                    case "content-type":
                        request.ContentType = hd.Value;
                        break;
                    case "transfer-enconding":
                        request.TransferEncoding = hd.Value;
                        break;
                    default:
                        request.Headers.Add(hd.Key, hd.Value);
                        break;
                }
            }
        }


        /// 
        /// 格式化Get请求参数
        /// 
        /// URL
        /// 参数
        /// 编码格式
        /// 

        private static string FormatGetParametersToUrl(string url, Dictionary parameters, Encoding paraEncoding)
        {
            if (url.IndexOf("?") < 0)
                url += "?";
            int i = 0;
            string sendContext = "";
            foreach (var parameter in parameters)
            {
                if (i > 0)
                {
                    sendContext += "&";
                }

                sendContext += HttpUtility.UrlEncode(parameter.Key, paraEncoding)
                       + "=" + HttpUtility.UrlEncode(parameter.Value, paraEncoding);
                ++i;
            }

            url += sendContext;
            return url;
        }


        /// 
        /// 格式化Post请求参数
        /// 
        /// 编码格式
        /// 编码格式
        /// 类型
        /// 
        private static byte[] FormatPostParameters(Dictionary parameters, Encoding dataEncoding, string contentType)
        {
            string sendContext = "";
            int i = 0;
            if (!string.IsNullOrEmpty(contentType) && contentType.ToLower().Trim() == "application/json")
            {
                sendContext = "{";
            }

            foreach (var para in parameters)
            {
                if (!string.IsNullOrEmpty(contentType) && contentType.ToLower().Trim() == "application/json")
                {
                    if (i > 0)
                    {
                        if (para.Value.StartsWith("{"))
                        {
                            sendContext += string.Format(@",""{0}"":{1}", para.Key, para.Value);
                        }
                        else
                        {
                            sendContext += string.Format(@",""{0}"":""{1}""", para.Key, para.Value);
                        }

                    }
                    else
                    {
                        if (para.Value.StartsWith("{"))
                        {
                            sendContext += string.Format(@"""{0}"":{1}", para.Key, para.Value);
                        }
                        else
                        {
                            sendContext += string.Format(@"""{0}"":""{1}""", para.Key, para.Value);
                        }

                    }
                }
                else
                {
                    if (i > 0)
                    {
                        sendContext += string.Format("&{0}={1}", para.Key, HttpUtility.UrlEncode(para.Value, dataEncoding));
                    }
                    else
                    {
                        sendContext = string.Format("{0}={1}", para.Key, HttpUtility.UrlEncode(para.Value, dataEncoding));
                    }
                }

                i++;
            }

            if (!string.IsNullOrEmpty(contentType) && contentType.ToLower().Trim() == "application/json")
            {
                sendContext += "}";
            }

            byte[] data = dataEncoding.GetBytes(sendContext);
            return data;
        }


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

调用方法:

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

namespace HttpHelperNamespace
{
    public  class HttpTest
    {
        public  void Test()
        {
            //GET http://interface.sina.cn/wap_api/layout_col.d.json?&showcid=56261
            var reqGET = HttpHelper.HttpRequest(
                 "GET"    //string getOrPost,
                , "http://interface.sina.cn/wap_api/layout_col.d.json?&showcid=56261"    //string url,
                , null    //List < KeyValuePair < string, string >> headers,
                , null    //List < KeyValuePair < string, string >> parameters,
                , Encoding.UTF8                    //Encoding dataEncoding,
                , "application/x-www-form-urlencoded;charset=utf-8"                                   //string contentType
                );

            System.IO.StreamReader readerGET;
            readerGET = new System.IO.StreamReader(reqGET.GetResponseStream(), Encoding.UTF8);
            var respHTML = readerGET.ReadToEnd();  //得到响应结果
            readerGET.Close();
            reqGET.Close();

            

            POST http://interface.sina.cn/wap_api/layout_col.d.json?&showcid=56261
            Dictionary dict = new Dictionary();
            dict.Add("showcid", "56261");

            var reqPOST = HttpHelper.HttpRequest(
                 "POST"    //string getOrPost,
                , "http://interface.sina.cn/wap_api/layout_col.d.json"    //string url,
                , null    //List < KeyValuePair < string, string >> headers,
                , dict    //List < KeyValuePair < string, string >> parameters,
                , Encoding.UTF8                    //Encoding dataEncoding,
                , "application/x-www-form-urlencoded;charset=utf-8"                                   //string contentType
                );

            System.IO.StreamReader readerPOST;
            readerPOST = new System.IO.StreamReader(reqPOST.GetResponseStream(), Encoding.UTF8);
            var respHTMLPOST = readerPOST.ReadToEnd(); //得到响应结果
            readerPOST.Close();
            reqPOST.Close();

        }  
    }
}

c# HttpHelper类 Http请求通用方法_第1张图片

你可能感兴趣的:(C#,ASP.NET)