[英]Get zip file from RestRequest
For REST calls I use RestSharp, I have to call a service that has to return me a zip file which I will then save on File System对于 REST 调用,我使用 RestSharp,我必须调用一个必须向我返回 zip 文件的服务,然后我将其保存在文件系统上
public bool DownloadZip(int id)
{
while (true)
{
var request = new RestRequest("download/zip", DataFormat.Json);
request.AddHeader("authorization", _token);
request.AddHeader("ID", _id.ToString());
request.AddQueryParameter("id", id.ToString());
var response = new RestClient(url).Get(request);
response.ContentType = "application/zip";
_logFile.Debug($"downloaded result {id}: {response.IsSuccessful} {response.StatusCode}");
if (response.IsSuccessful && !string.IsNullOrWhiteSpace(response.Content))
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
{
using (var zip = File.OpenWrite(path: @"C:\temp\temp.zip"))
{
zip.CopyTo(stream);
}
}
return true;
}
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
_logFile.Warn($"Download Unauthorized {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
_authToken = null;
}
else
{
_logFile.Error($"Download {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
throw new Exception("DownloadZip Failed");
}
}
}
The line of code " zip.CopyTo(stream);
" returns "The stream does not support reading" as an error.代码行“ zip.CopyTo(stream);
”返回“stream 不支持读取”作为错误。 Is there any setting to set to ensure that it does not return an error?是否有任何设置可以确保它不返回错误? Testing the call on Postman I noticed that in the response header I have Content-Disposition from this can I go back to the filename?在 Postman 上测试调用我注意到在响应 header 中我有 Content-Disposition ,我可以 go 回到文件名吗?
With RestSharp 107 you can use使用 RestSharp 107,您可以使用
var stream = await client.DownloadStreamAsync(request);
It will give you a stream and you can do whatever you want with it.它会给你一个 stream,你可以用它做任何你想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.