轉 c#代碼訪問https服務器以及https的webservice

最近公司作到WebService項目,可是要經過Https調用,本身在網上搜了半天,終於實現了服務端的Https,可是一直沒有找到客戶端如何實現,今天終於看到這篇文章,隨手記錄下來。web

具體代碼以下:瀏覽器

訪問https的web服務器

 public static void ProcessRequest()
        {
            //相似瀏覽器確認證書合法方法的綁定
            ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://yourUrl");

            string param = "test=true";
            byte[] bs = Encoding.UTF8.GetBytes(param);

            //這2句代碼表示若是要求客戶端證書,將客戶端證書加入request,不須要客戶端證書的https請求則不須要此代碼
            X509Certificate cer = new X509Certificate("D:\\tt.cer");
            request.ClientCertificates.Add(cer);

            request.UserAgent = "test";
            request.Method = "post";

            using (Stream reqStram = request.GetRequestStream())
            {
                reqStram.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
            
            Console.ReadKey();
        }
        //該方法用於驗證服務器證書是否合法,固然能夠直接返回true來表示驗證永遠經過。服務器證書具體內容在參數certificate中。可根據我的需求驗證
        //該方法在request.GetResponse()時觸發
        public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            return false;
        }

訪問https的web service基本類同,首先添加對https的web引用。post

在代碼中:ssl

 

public static void WebRefrence()
        {
            //若是以爲寫一個委託方法麻煩,能夠直接使用匿名委託
            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, 
                X509Chain chain, SslPolicyErrors errors)
            {
                if (errors == SslPolicyErrors.None)
                    return true;
                return false;
            };

            //建立web引用的實例
            WebReference.Service ws = new WebReference.Service();

            //提供客戶端證書,不要求的能夠忽略該步驟
            ws.ClientCertificates.Add(new X509Certificate("D:\\tt.cer"));
            //執行web service中提供的方法,該例中爲將傳入的2個int相加並返回結果
            int r = ws.Add(4, 5);
            Console.WriteLine(r);
            Console.ReadKey();
        }
相關文章
相關標籤/搜索