Download Files using C# from https Website

半城伤御伤魂 提交于 2019-12-13 08:09:05

问题


I'm trying to download a pdf file from https website, but it doesn't work. I'm new to C#, so did some research and found a simple code. Worse, the exception I get is quite generic. Help please.

    static void Main(string[] args)
    {

        string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
        string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

        WebClient wc_ = new WebClient();
        wc_.DownloadFile(file_, path_);
    }

The exception: An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The remote server returned an error: (403) Forbidden.


回答1:


The server is checking to see if you're a real user by using your user agent header. It also requires that you specify the mime type you want. This isn't a general C# thing, it's just the host you're connecting to (nseindia.com).

This works for me.

static void Main(string[] args)
{

    string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
    string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

    WebClient wc_ = new WebClient();
    wc_.Headers.Add(HttpRequestHeader.UserAgent, "Other");
    wc_.Headers.Add(HttpRequestHeader.Accept, "application/pdf");
    wc_.DownloadFile(file_, path_);
}



回答2:


public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}

static void Main(string[] args)
{
    string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
    string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

    WebClient wc_ = new WebClient();
    wc_.Headers.Add(HttpRequestHeader.UserAgent, "Other");
    wc_.Headers.Add(HttpRequestHeader.Accept, "application/pdf");
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
    wc_.DownloadFile(file_, path_);
}


来源:https://stackoverflow.com/questions/43165859/download-files-using-c-sharp-from-https-website

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!