Recently the company to do WebService project, but to call through HTTPS, their own search on the internet for half a day, and finally realize the service side of the HTTPS, but has not found how to achieve the client, today finally see this article, readily recorded.
The specific code is as follows:
Web Access to HTTPS
public static void ProcessRequest () {//Like the browser confirms the binding of the certificate legal method Servicepointmanager.servercertifica Tevalidationcallback = Remotecertificatevalidationcallback; HttpWebRequest request = (HttpWebRequest) webrequest.create ("Https://yourUrl"); string param = "Test=true"; byte[] bs = Encoding.UTF8.GetBytes (param); These 2 lines of code indicate that if a client certificate is required, the client certificate is added to the request, and the HTTPS request does not require a client certificate, this code is not required x509certificate cer = new X509Certificate ("D:\\tt.ce R "); 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 (); }//This method is used to verify that the server certificate is legitimate and can, of course, return true directly to indicate that the validation passed forever. The server certificate details are in the parameter certificate. can be verified according to individual requirements//This method is in request. GetResponse () triggers public static bool Remotecertificatevalidationcallback (object sender, X509Certificate certificate, X509chain chain, sslpolicyerrors sslpolicyerrors) {if (sslpolicyerrors = = Sslpolicyerrors.none) return true; return false; }
A Web service that accesses https is basically similar, first adding a Web reference to HTTPS.
In the code:
public static void Webrefrence () { //If you find it troublesome to write a delegate method, you can use the anonymous delegate directly Servicepointmanager.servercertificatevalidationcallback = Delegate (object sender, X509Certificate certificate, X509chain chain, sslpolicyerrors errors) { if (errors = = Sslpolicyerrors.none) return true; return false; }; Create an instance of the Web reference webreference.service ws = new Webreference.service (); Provides a client certificate that is not required to ignore the step ws. Clientcertificates.add (New X509Certificate ("D:\\tt.cer")); Executes the method provided in the Web service, which adds the incoming 2 int and returns the result int r = ws. ADD (4, 5); Console.WriteLine (r); Console.readkey (); }
Go to C # code access HTTPS server and HTTPS WebService