HttpClient返回0个字节

时间:2019-08-09 16:31:33

标签: c# .net-core httpclient

GetByteArrayAsyncGetStreamAsync均返回0字节或空流。我想将接收到的字节写到文件中。

我尝试使用byte[] stream = await _httpClient.GetByteArrayAsync("http://gscs-b2c.lge.com/downloadFile?fileId=BZhqND5RTnHcyMRDCeJJQ")_httpClient.GetStreamAsync("http://gscs-b2c.lge.com/downloadFile?fileId=BZhqND5RTnHcyMRDCeJJQ"),但是它们都返回0字节或空流。

我已尝试从PostMan进行获取请求,它返回了一个有效的PDF文件。我已经从浏览器中尝试过,它会返回有效的PDF文件。但是在代码中,它返回空文件(0字节)。我检查了其他答案,但仍然无法解决此问题。有趣的是,它可用于其他站点的其他pdf文件。

以下是我正在使用的.net Core 2.2中的示例代码

_client = new HttpClient();
_client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
_client.Timeout = TimeSpan.FromMinutes(2);

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

var downloadPdfLink = "http://gscs-b2c.lge.com/downloadFile?fileId=BZhqND5RTnHcyMRDCeJJQ";
using (Stream stream = await _client.GetStreamAsync(downloadPdfLink))
{
    using (var fs = new FileStream("./file/myfile.pdf",FileMode.CreateNew,FileAccess.Write))
    {
        //stream.Seek(0, SeekOrigin.Begin);
        stream.CopyTo(fs);
    }
}

预期结果应该是将返回的流写入“ myfile.pdf”。您能帮我了解这里的问题是什么,我做错了什么?

1 个答案:

答案 0 :(得分:1)

通过网络浏览器下载compile文件时,我在开发人员工具中注意到,其他标头已添加到请求中: compile等将返回响应内容中的文件,而不是像原始代码中那样将其长度设置为0。

有几种方法可以修复代码:

HttpClient.DefaultRequestHeaders

.pdf

HttpClientHandler.AutomaticDecompression

Accept-Encoding: gzip, deflate

HttpRequestHeaders.AcceptEncoding

_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
_client.DefaultRequestHeaders.Add("Accept-Encoding", "deflate");

并且要提醒您,一旦完成操作,别忘了var handler = new HttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; var _client = new HttpClient(handler); 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); } } }