如何在网页中发送帖子请求并获取 pdf 文件

本文关键字:请求 获取 文件 pdf 网页 | 更新日期: 2023-09-27 18:35:43

我正在编写一个 C# 控制台应用程序,并且正在使用 Web 客户端从网页下载一些文件。 问题是当我提供直接下载 URL 以使用 Web 客户端下载文件时,它会返回 404 错误。我想要的是使用post请求打开页面,然后使用该页面中的url启动下载。我不明白如何使用 post 请求调用该页面以及如何通过它下载文件。我是编程新手,所以我希望这样它能工作。

这是页面 :

这就是我到目前为止尝试的,但没有奏效。

 private void DownloadFile(string fileType, string list)
    {
        try
        {
            WebClient webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "http://www.munifilings.com/munifilings/speedSearch.do?affiliateId=97&memberId=MPSNQTVY1CGKAEI&cusip=738855DC6");
            webClient.DownloadFile("http://munifilings.com/pdfs/0/" + list + ".pdf", @"E:''New''CUSIPS_" + fileType + "_" + list + ".pdf");
            Console.WriteLine("Downloaded: CUSIPS_" + fileType + "_" + list + ".pdf");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error" + ex.Message);
            throw;
        }
    }

错误

如何在网页中发送帖子请求并获取 pdf 文件

你来了。您需要发送Referer标头,它是 GET,而不是 POST 请求。

try
{
    WebClient wc = new WebClient();
    wc.Headers.Add(HttpRequestHeader.Referer, "http://www.munifilings.com/munifilings/speedSearch.do?affiliateId=97&memberId=MPSNQTVY1CGKAEI&cusip=738855HJ7");
    wc.DownloadFile("http://munifilings.com/pdfs/0/k36062.pdf", @"D:'pathToFile");
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}
Console.ReadLine();

对于其他网址,您必须更改引用者地址。例:

WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Referer, "http://www.munifilings.com/munifilings/multiThreaded.do?method=DIRECT&fileType=MAVEN&list=k15547");
wc.DownloadFile("http://munifilings.com/pdfs/0/k15547.pdf", @"D:'pathToFile2");

和:

WebClient wc = new WebClient();
    wc.Headers.Add(HttpRequestHeader.Referer, "http://www.munifilings.com/munifilings/multiThreaded.do?method=DIRECT&fileType=MAVEN&list=i83453");
    wc.DownloadFile("http://munifilings.com/pdfs/0/i83453.pdf", @"D:'pathToFile4.pdf");