简体   繁体   English

如何使用 httpclient 指定下载文件的目标

[英]How do I specify the destination to download the file using httpclient

I have the need to convert this PS cmdlet to C#我需要将此 PS cmdlet 转换为 C#

invoke-webrequest -uri [uri] -method GET -headers [myHeader] -outfile  [myFile]

where [uri] is the download link, [myHeader] contains my apikey and my outfile is the name of the destination file.其中 [uri] 是下载链接,[myHeader] 包含我的 apikey,我的 outfile 是目标文件的名称。

The invoke-webrequest in PS works but my project requires C# code. PS中的invoke-webrequest有效,但我的项目需要C#代码。 I can use the following code for the normal get or post action if I were dealing with the standard json:如果我正在处理标准 json,我可以将以下代码用于正常的 get 或 post 操作:

        var msg = new HttpRequestMessage(HttpMethod.Get, [uri]);
        msg.Headers.Add(_apiKeyTag, _myKey);
        var resp = await _httpClient.SendAsync(msg);

Assuming _httpClient is created by new HttpClient and assuming the download link [uri] exists.假设 _httpClient 由 new HttpClient 创建并假设下载链接 [uri] 存在。 The file to be downloaded is either a pdf, jpg, img or csv file.要下载的文件是 pdf、jpg、img 或 csv 文件。 I am not sure how to convert the above comdlet in PS to C#.我不确定如何将 PS 中的上述 comdlet 转换为 C#。

How do I specify my destination file?如何指定我的目标文件? (I am referring to the option -outfile in PS) (我指的是PS中的选项-outfile)

Never use anything but HttpClient .切勿使用除HttpClient之外的任何东西。 If you catch yourself typing WebClient of anything other than HttpClient , kindly slap your hand away from the keyboard.如果你发现自己在输入除HttpClient以外的任何东西的WebClient ,请把你的手从键盘上拿开。

You want to download a file with HttpClient ?您想使用HttpClient下载文件吗? Here is an example of how to do that:以下是如何执行此操作的示例:

private static readonly HttpClient _httpClient = new HttpClient();

private static async Task DoSomethingAsync()
{
    using (var msg = new HttpRequestMessage(HttpMethod.Get, new Uri("https://www.example.com")))
    {
        msg.Headers.Add("x-my-header", "the value");
        using (var req = await _httpClient.SendAsync(msg))
        {
            req.EnsureSuccessStatusCode();
            using (var s = await req.Content.ReadAsStreamAsync())
            using (var f = File.OpenWrite(@"c:\users\andy\desktop\out.txt"))
            {
                await s.CopyToAsync(f);
            }
        }
    }
}

You can do anything you want with HttpClient .你可以用HttpClient任何你想做的事情。 No reason to use RestClient , WebClient , HttpWebRequest or any of those other "wannabe" Http client implementations.没有理由使用RestClientWebClientHttpWebRequest或任何其他“想要的” Http 客户端实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM