问题描述
我需要将此PS cmdlet转换为C#
invoke-webrequest -uri [uri] -method GET -headers [myHeader] -outfile [myFile]
其中[uri]是下载链接,[myHeader]包含我的apikey,我的outfile是目标文件的名称。
PS中的invoke-webrequest可以工作,但是我的项目需要C#代码。如果我正在处理标准json,则可以将以下代码用于正常的get或post操作:
var msg = new HttpRequestMessage(HttpMethod.Get,[uri]);
msg.Headers.Add(_apiKeyTag,_myKey);
var resp = await _httpClient.SendAsync(msg);
假定_httpClient由新的HttpClient创建,并假定存在下载链接[uri]。要下载的文件是pdf,jpg,img或csv文件。 我不确定如何将PS中的上述comdlet转换为C#。
如何指定目标文件? (我指的是PS中的-outfile选项)
解决方法
除HttpClient
外,请勿使用其他任何东西。如果您发现自己输入了WebClient
以外的其他任何内容,请从键盘上拍打HttpClient
。
您要使用HttpClient
下载文件吗?这是如何执行此操作的示例:
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);
}
}
}
}
您可以使用HttpClient
做任何您想做的事。没有理由使用RestClient
,WebClient
,HttpWebRequest
或其他任何“想要的” Http客户端实现。