.net 在winrt中下载文件,使用HttpClient或HttpWebRequest或BackgroundDownloader?
我想使用HttpClient或HttpWebRequest或BackgroundDownloader下载文件 在发送请求之前,我需要修改http头“Range”和“Cookie”,并获取下载进度值 现在的问题是HttpClient可以修改“范围”标题,但无法获得下载进度。HttpWebRequest可以获得下载进度,但无法修改“范围”标题。BackgroundDownloader无法修改“Cookie”标题。这是一个链接.net 在winrt中下载文件,使用HttpClient或HttpWebRequest或BackgroundDownloader?,.net,windows-8,microsoft-metro,windows-runtime,.net,Windows 8,Microsoft Metro,Windows Runtime,我想使用HttpClient或HttpWebRequest或BackgroundDownloader下载文件 在发送请求之前,我需要修改http头“Range”和“Cookie”,并获取下载进度值 现在的问题是HttpClient可以修改“范围”标题,但无法获得下载进度。HttpWebRequest可以获得下载进度,但无法修改“范围”标题。BackgroundDownloader无法修改“Cookie”标题。这是一个链接 我该怎么办?在WinRT下,您可以借助操作上下文范围修改消息头。我不确定它
我该怎么办?在WinRT下,您可以借助
操作上下文范围
修改消息头。我不确定它是否适用于HttpClient
,但适用于HttpWebRequest
,请参见示例。我只是偶然发现了这个问题。使用HttpClient,您可以获得下载进度(假定服务器发送内容长度标头)。以下示例将返回的内容读取到(文件)流中,并在下载时计算进度。重要的一点是,在任何内容可用且标头已发送时,传递HttpCompletionOption.ResponseHeadersRead以获得响应
Uri uri = ...
// Request the data
HttpResponseMessage responseMessage = await httpClient.GetAsync(uri,
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
// Get the size of the content
long? contentLength = responseMessage.Content.Headers.ContentLength;
// Create a stream for the destination file
StorageFile destinationFile = await destinationFolder
.CreateFileAsync(destinationFileName,
CreationCollisionOption.ReplaceExisting);
using (Stream fileStream =
await destinationFile.OpenStreamForWriteAsync())
{
// Read the content into the file stream
int totalNumberOfBytesRead = 0;
using (var responseStream =
await responseMessage.Content.ReadAsStreamAsync())
{
int numberOfReadBytes;
do
{
// Read a data block into the buffer
const int bufferSize = 1048576; // 1MB
byte[] responseBuffer = new byte[bufferSize];
numberOfReadBytes = await responseStream.ReadAsync(
responseBuffer, 0, responseBuffer.Length);
totalNumberOfBytesRead += numberOfReadBytes;
// Write the data block into the file stream
fileStream.Write(responseBuffer, 0, numberOfReadBytes);
// Calculate the progress
if (contentLength.HasValue)
{
// Calculate the progress
double progressPercent = (totalNumberOfBytesRead /
(double)contentLength) * 100;
// Display the progress
...
}
else
{
// Just display the read bytes
...
}
} while (numberOfReadBytes != 0);
}
}
我在我的库中实现了非常简单的HTTP类。这些类支持Cookie、头的设置,还支持进度报告的IProgress(以及更多)
请查看此站点上的示例代码:
HttpWebRequest
可以仅在.Net framework中使用.AddRange()方法修改Range
头,而不使用winrt