C# POST Https請求的一些坑

寫在前面:

  從上次,跟合做方的站點對接開始就產生了這個問題,當時用C#進行POST提交,老是會出現問題,找了好久發現對方的站點竟然是TLS 1.2 的。app

正文:

然而,在.NET FrameWork 4.0的環境下,竟然找不到。。。System.Net.SecurityProtocolType 這個枚舉,沒有這個值。。。post

因此,在POST提交的時候,是會出現問題,有的網站就不會有這個問題,由於他們是1.0的。網站

  因此啊,感受這就是一個坑,好在,即便沒有現成的,1.2咱們也是能夠用代碼來實現1.2的url

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;  //SecurityProtocolType.Tls1.2;

    固然,若是是4.0之後的環境,查看這個枚舉是能夠看到不一樣的值的。spa

namespace System.Net
{
    using System;
    
    [Flags]
    public enum SecurityProtocolType
    {
        Ssl3 = 0x30,
        Tls = 0xc0,
        Tls11 = 0x300,
        Tls12 = 0xc00
    }
}

,,,,到這裏,該說的,都說了,最後附上,C#  https POST的代碼吧。code

    class ProgramTest
    {
        static void Main(string[] args)
        {
            string url = "https://www.test.com";
            string result = PostUrl(url, "key=123"); // key=4da4193e-384b-44d8-8a7f-2dd8b076d784
            Console.WriteLine(result);
            Console.WriteLine("OVER");
            Console.ReadLine();
        }

        private static string PostUrl(string url, string postData)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
         // 這裏設置了協議類型。 ServicePointManager.SecurityProtocol
= (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } else { request = (HttpWebRequest)WebRequest.Create(url); } request.Method = "POST"; //使用get方式發送數據 request.ContentType = "application/x-www-form-urlencoded"; request.Referer = null; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; byte[] data = Encoding.UTF8.GetBytes(postData); Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); //獲取網頁響應結果 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string result = string.Empty; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //老是接受 } }
相關文章
相關標籤/搜索