问题
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