1 回答
TA贡献1898条经验 获得超8个赞
通过网络浏览器下载.pdf文件时,我注意到在开发人员工具中,附加标头被添加到请求中: Accept-Encoding: gzip, deflate等等,这将在响应内容中携带文件,而不是留下长度0 就像你的原始代码一样。
有多种方法可以修复代码:
HttpClient.DefaultRequestHeaders
_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); _client.DefaultRequestHeaders.Add("Accept-Encoding", "deflate");
HttpClientHandler.AutomaticDecompression
var handler = new HttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; var _client = new HttpClient(handler);
HttpRequestHeaders.AcceptEncoding
var request = new HttpRequestMessage(HttpMethod.Get, downloadPdfLink);
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
using (HttpResponseMessage response = await _client.SendAsync(request))
{
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
Directory.CreateDirectory("./file");
using (var fs = new FileStream("./file/myfile.pdf", FileMode.Create, FileAccess.Write))
{
//stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fs);
}
}
}
并且,作为一个友好的提醒,一旦你完成了它,不要忘记Dispose()你的。HttpClient
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报