凌的博客

您现在的位置是: 首页 > 学无止境 > PHP > 

PHP

C#的HttpHelper类post ,get

2016-05-17 PHP 1476
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Tex
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sslUrl
{
    class HttpHelper
    {
        private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36";
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        public static string get(String requestURL)
        {
            //Dictionary HeaderList = new Dictionary();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestURL);
            request.KeepAlive = true;
            HttpWebResponse reponse = null;
            Stream stream = null;
            string strResponse = string.Empty;
            try
            {
                //URI scheme(抽象标识符体系): 若为"https"则需加载证书并验证
                if (request.RequestUri.Scheme == "https")
                {
                    #region 加载证书
                    //挂接验证服务端证书的回调
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);

                    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                    //获取本地主机名称作为证书查找的参数
                    string findValue = Dns.GetHostName();
                    X509Certificate2Collection _certsCollection = store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false);

                    X509Certificate2 x509c = null;

                    // MessageBox.Show("证书个数: " + _certsCollection.Count);
                    //strResponse += "证书个数: " + _certsCollection.Count + "\n\n";
                    if (_certsCollection.Count > 0)
                    {
                        //MessageBox.Show("有证书");
                        x509c = _certsCollection[0];
                        request.ClientCertificates.Add(x509c);
                    }
                    else
                    {
                        //MessageBox.Show("没有证书");
                    }
                    #endregion
                }

                request.Timeout = 30000;
             
                request.UserAgent = DefaultUserAgent;
                //request.Referer = "www.baidu.com";
                request.Method = "GET";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded";

                request.AllowAutoRedirect = false;
                request.Headers.GetValues("Location");

                reponse = (HttpWebResponse)request.GetResponse();

                //foreach (string HeaderKey in reponse.Headers)
                //{
                //    strResponse += HeaderKey + ": " + reponse.Headers[HeaderKey] + "\n";
                //}

                //strResponse += "\n\n";
                //MessageBox.Show("StatusCode = " + reponse.StatusCode);
                //strResponse += "StatusCode = " + reponse.StatusCode + "\n\n";

                if (reponse.StatusCode == HttpStatusCode.OK)
                {
                    stream = reponse.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(stream, Encoding.UTF8);
                    strResponse += myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    stream.Close();
                }

            }
            catch (WebException ex)
            {
                //MessageBox.Show("异常1----" + ex);
                throw new WebException(ex.Message, ex.InnerException);
            }

            catch (Exception ex)
            {
                //MessageBox.Show("异常2----" + ex);
                throw new Exception(ex.Message, ex.InnerException);
            }

            finally
            {
                if (stream != null) { stream.Close(); }
                if (reponse != null) { reponse.Close(); reponse = null; }
                if (request != null) { request = null; }
            }

            //如果未收到负载均衡系统返回报文响应,抛出异常信息。
            if (string.IsNullOrEmpty(strResponse))
            {
                throw new Exception("警告:服务请求失败,负载均衡系统无响应,请确认服务请求已正确配置!");
            }

            //返回信息
            return strResponse;
        }


        public static bool RemoteCertificateValidationCallback(Object sender,
           X509Certificate certificate,
           X509Chain chain,
           SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static string post(string requestURL, IDictionary parameters, CookieCollection cookies) {
            string strResponse = string.Empty;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestURL);
            request.KeepAlive = true;
            HttpWebResponse reponse = null;
            Stream stream = null;
           
            try
            {
                //URI scheme(抽象标识符体系): 若为"https"则需加载证书并验证
                if (request.RequestUri.Scheme == "https")
                {
                    #region 加载证书
                    //挂接验证服务端证书的回调
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);

                    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                    //获取本地主机名称作为证书查找的参数
                    string findValue = Dns.GetHostName();
                    X509Certificate2Collection _certsCollection = store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false);

                    X509Certificate2 x509c = null;

                    // MessageBox.Show("证书个数: " + _certsCollection.Count);
                    //strResponse += "证书个数: " + _certsCollection.Count + "\n\n";
                    if (_certsCollection.Count > 0)
                    {
                        //MessageBox.Show("有证书");
                        x509c = _certsCollection[0];
                        request.ClientCertificates.Add(x509c);
                    }
                    else
                    {
                        //MessageBox.Show("没有证书");
                    }
                    #endregion
                }

                request.Timeout = 30000;

                request.UserAgent = DefaultUserAgent;
                //request.Referer = "www.baidu.com";
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded";

                request.AllowAutoRedirect = false;
                request.Headers.GetValues("Location");

                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                //发送POST数据  
                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 = Encoding.ASCII.GetBytes(buffer.ToString());
                    using (stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                string[] values = request.Headers.GetValues("Content-Type");

                reponse = (HttpWebResponse)request.GetResponse();

                if (reponse.StatusCode == HttpStatusCode.OK)
                {                    
                    StreamReader myStreamReader = new StreamReader(stream, Encoding.UTF8);
                    strResponse += myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    stream.Close();
                }

            }
            catch (WebException ex)
            {
                //MessageBox.Show("异常1----" + ex);
                throw new WebException(ex.Message, ex.InnerException);
            }

            catch (Exception ex)
            {
                //MessageBox.Show("异常2----" + ex);
                throw new Exception(ex.Message, ex.InnerException);
            }

            finally
            {
                if (stream != null) { stream.Close(); }
                if (reponse != null) { reponse.Close(); reponse = null; }
                if (request != null) { request = null; }
            }

            //如果未收到负载均衡系统返回报文响应,抛出异常信息。
            if (string.IsNullOrEmpty(strResponse))
            {
                throw new Exception("警告:服务请求失败,负载均衡系统无响应,请确认服务请求已正确配置!");
            }

            return strResponse;
        }
        
    }
}

文章评论

0条评论