Accessing HTTPS URL from Console Application using C#

前端 未结 3 1774
名媛妹妹
名媛妹妹 2021-01-06 21:44

I want my application to hit the HTTPS URL specified and download the CSV file from that URL.

I have the following code:

Program.cs

相关标签:
3条回答
  • 2021-01-06 22:30

    Change this line:

    ServicePointManager.ServerCertificateValidationCallback =
         new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
    

    to this:

    ServicePointManager.ServerCertificateValidationCallback = (a,b,c,d) => { return true;};
    

    And you can get rid of the other code you have. The problem with your code is that you were referencing the static AcceptAllCertifications, which you never set. So it always had a null, which in turn meant that you were not acutally assigning a value to it.

    0 讨论(0)
  • 2021-01-06 22:32

    This code did the trick for me:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.IO;
    
    namespace ReadCSVFromURL
    {
        class Program
        {
            static void Main(string[] args)
            {
                SplitCSV();
            }
    
            public static string GetCSV(string url)
            {
    
                ServicePointManager.ServerCertificateValidationCallback = 
                (object a, System.Security.Cryptography.X509Certificates.X509Certificate b, System.Security.Cryptography.X509Certificates.X509Chain c, System.Net.Security.SslPolicyErrors d) => { return true; };            
    
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string results = sr.ReadToEnd();
                sr.Close();
    
                return results;
            }
            public static void SplitCSV()
            {
                List<string> splitted = new List<string>();
                string fileList = GetCSV("URL");
                string[] tempStr;
                tempStr = fileList.Split(',');
                foreach (string item in tempStr)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        splitted.Add(item);
                    } 
                }
            }
        }
    }
    

    Anyone who improves this code by providing a solution without bypassing Certificate validation will be marked as accepted.

    0 讨论(0)
  • 2021-01-06 22:45

    It seems your certificate is not trusted. You can disable certificate validation or make certificate to be trusted (put certificate under trusted root manually, for example).

    see SSL Certificate Issue - The remote certificate is invalid according to the validation procedure

    0 讨论(0)
提交回复
热议问题