How can I use C# HttpClient to download a part of large file, like HttpWebRequest.AddRange(123)?
public async void StartDownload(CancellationToken cancellationToken)
{
try
{
if (_isWork)
return;
_isWork = true;
using (var response = await GetAsync(_doenloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
await DownloadFileFromHttpResponseMessage(response);
}
catch (Exception e)
{
downloadExceptiondHandler?.Invoke(_doenloadUrl, e);
}
}
There is a Range
header specified in the HTTP protocol for that very purpose:
The Range HTTP request header indicates the part of a document that the server should return. [...] The server can also ignore the Range header and return the whole document with a 200 status code. (source , emphasis mine)
Therefor you cannot rely on the server returning only that range of the file.
However, in a HttpRequest
there is a property Range
in HttpRequestHeaders
to set the Range
of a request
private async Task<HttpResponseMessage> GetAsync(string downloadUrl,
int rangeStart,
int rangeEnd)
{
// Beware: C# 8, use a using block with older language specifications
using var request = new HttpRequestMessage
{
RequestUri = new Uri(donloadUrl),
Method = HttpMethod.Get
};
request.Headers.Range = new RangeHeaderValue(rangeStart, rangeEnd);
return await _httpClient.SendRequestAsync(request);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.