从https网站使用C#下载文件 [英] Download Files using C# from https Website

查看:967
本文介绍了从https网站使用C#下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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).

这对我有用。

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

这篇关于从https网站使用C#下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆