使用C#从API下载PDF文件 [英] Download PDF File from API Using C#

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

问题描述

我正在创建一个控制台应用程序

I am creating a console application that

  1. 连接到供应商API以提取两个日期之间提交的费用的凭证编号,并且
  2. 下载带有费用提交的收据的PDF副本

第一部分,我工作正常.我可以使用以下代码连接到Vendor API并解析出返回的XML,以创建凭证编号数组(需要获取PDF图像):

The first part, I have working fine. I am able to connect to the Vendor API and parse out the returned XML to create an array of voucher numbers (needed to get the PDF images) using the following code:

static async Task RunAsyncCR()
        {
            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                    {"un","SomeUser"},
                    {"pw","SomePassword"},
                    {"method","getVoucherInvoices"},
                    {"fromDate","05/30/2016"},
                    {"toDate", "06/13/2016"}
                };

                var content = new FormUrlEncodedContent(values);

                Console.WriteLine("Connecting...");

                var response = await client.PostAsync("https://www.chromeriver.com/receipts/doit", content);

                Console.WriteLine("Connected...");

                var responseString = await response.Content.ReadAsStringAsync();

                char[] DelimiterChars = {'<'};

                String[] xmlReturn = responseString.Split(DelimiterChars);

                string[] VoucherNumber = new string[500];

                int i = 0;

                foreach (string s in xmlReturn)
                {
                    if (s.Contains("voucherInvoice>") && s != "/voucherInvoice>\n    ")
                    {
                        VoucherNumber[i] = s.Substring(15, 16);

                        i++;
                    }
                }

                Array.Resize(ref VoucherNumber, i);

是的,可能有更好的方法,但是它可以工作并返回我期望的值.

Yes, there is likely a better way of doing this, but it works and returns the values I am expecting.

现在,我遇到的麻烦是,当我重新连接到API来检索文件时,似乎无法将文件下载到指定的文件路径.

Now, what I am having trouble with, is when I connect back to the API to retrieve the file, I cannot seem to be able to download the file to a specified file path.

我可以使用连接回API

I can connect back to the API using

            i = 0;

            foreach (string x in VoucherNumber)
            {
                Console.WriteLine("Get receipt: " + x);

                var NewValues = new Dictionary<string, string>
                {
                    {"un","SomeUser"},
                    {"pw","SomePassword"},
                    {"method","getReceiptsWithCoverPage"},
                    {"voucherInvoiceForPdf", VoucherNumber[i]}
                };

                var NewContent = new FormUrlEncodedContent(NewValues);

                var NewResponse = await client.PostAsync("https://www.chromeriver.com/receipts/doit", NewContent);

                string NewResponseString = await NewResponse.Content.ReadAsStringAsync();

但是我似乎无法将回复写到有效文件(PDF)

But I cannot seem to write the response to a valid file (PDF)

这是我逐步查看代码时的汽车"窗口的屏幕截图,我需要在其中下载文件:

Here is a screen shot of my Autos window as I step through the code, where I would need to download the file:

我的问题是,从现在开始,如何将文件保存到系统中?

我已经尝试从执行 Console.WriteLine(NewResponseString); 时获得的编码响应,然后使用 System.IO.File.WriteAllLines()方法,使用指定的文件路径/名称,但这会导致文件为空.我还花了一些时间研究Google/Stackoverflow的深度,但不了解如何实现我发现的结果.

I have tried to take the encoded response I get from doing Console.WriteLine(NewResponseString); and write it to a file using the System.IO.File.WriteAllLines() method, using a specified filepath/name, but this results in a blank file. I have also spent some time researching the depths of Google/Stackoverflow, but do not understand how to implement the results I find.

任何人和所有帮助将不胜感激.

Any and all help would be greatly appreciated.

推荐答案

所以我认为您需要有关Streams的帮助.返回的 HttpContent 实际上是一个 System.Net.Http.StreamContent 实例,该实例表明您正在获取内容.只需从该实例获取流(内容)并将其保存到文件即可.

So I think you need help with Streams. The returned HttpContent is actually a System.Net.Http.StreamContent instance which shows that you are getting content back. Its just a matter of getting the Stream (content) from that instance and saving that to a file.

var NewResponse = await client.PostAsync("https://www.chromeriver.com/receipts/doit", NewContent);

System.Net.Http.HttpContent content = NewResponse.Content; // actually a System.Net.Http.StreamContent instance but you do not need to cast as the actual type does not matter in this case

using(var file = System.IO.File.Create("somePathHere.pdf")){ // create a new file to write to
    var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream
    await contentStream.CopyToAsync(file); // copy that stream to the file stream
}


我谨建议您对Streams的工作方式进行一些阅读.这是许多语言中的常见构造,您可能会在不久的将来再次遇到这种情况.


I respectfully recommend that you do a little reading on how Streams work. This is a common construct in many languages that you will probably have to deal with again in the near future.

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

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