1 回答

TA貢獻(xiàn)1898條經(jīng)驗 獲得超8個贊
通過網(wǎng)絡(luò)瀏覽器下載.pdf文件時,我注意到在開發(fā)人員工具中,附加標(biāo)頭被添加到請求中: Accept-Encoding: gzip, deflate等等,這將在響應(yīng)內(nèi)容中攜帶文件,而不是留下長度0 就像你的原始代碼一樣。
有多種方法可以修復(fù)代碼:
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 關(guān)注
- 209 瀏覽
添加回答
舉報