November 12, 2019

How to Disable SSL verification while using HttpsURLConnection - C#

  November 12, 2019
If your website is not SSL secured, you can use below coded before sending a HTTP request to URL to bypass connection issue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
        public static void InitiateSSLTrust()
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(
                        delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
                        {
                            return true;
                        });
            }
            catch (Exception)
            {
                 // ActivityLog.InsertSyncActivity(ex);
            }
        }

InitiateSSLTrust() Will set the certificate and we have to call this before sending http requests.

Use below code to set the web requests to use default credentials in case the url is domain/proxy dependent

                HttpWebRequest webReq;
                webReq = (HttpWebRequest)WebRequest.Cr.eate(url);
                webReq.UseDefaultCredentials = true;
                webReq.UserAgent = "Link Checker";
                webReq.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Method to get response.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        public string GetHttpStatus(string url)
        {
            try
            {
                InitiateSSLTrust();
     
                HttpWebRequest webReq;
                webReq = (HttpWebRequest)WebRequest.Create(url);
                webReq.UseDefaultCredentials = true;
                webReq.UserAgent = "Link Checker";
                webReq.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                return response.StatusCode.ToString();

            }

            catch (Exception e)
            {
                return e.Message;
            }

        }
logoblog

Thanks for reading How to Disable SSL verification while using HttpsURLConnection - C#

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...