从https网站使用C#下载文件(Download Files using C# from https Website)

其他开发 IT屋
百度翻译此文   有道翻译此文
问 题

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.

解决方案

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_);
}

本文地址:IT屋 » Download Files using C# from https Website

问 题

我正在尝试从https网站下载pdf文件,但它不起作用。我是C#的新手,所以进行了一些研究,发现了一个简单的代码。更糟糕的是,我得到的例外是非常通用的。请帮助。



  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_);
}


例外:
类型'System.Net的未处理异常.WebException'发生在System.dll
附加信息:远程服务器返回错误:(403)Forbidden。


解决方案

服务器正在使用您的用户代理标头检查您是否是真实用户。它还要求您指定所需的mime类型。这不是一般 C#的东西,它只是你要连接的主机(nseindia.com)。



这对我有用。



  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_);
}

本文地址:IT屋 » 从https网站使用C#下载文件

官方微信
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起