具有Progress输出到控制台的HttpClient SendAsync

时间:2017-04-25 07:30:41

标签: c# dotnet-httpclient sendasync

我只是试着让一个基本的SendAsync方法将它的进度写入控制台,即使在为GET提供了大量的SO答案之后,我也没有真正看到它对POST的作用。

我正在测试的文件大约是100Mb,当它到达SendAsync方法时,它会一直持续到完成。

我可能会遗失什么?

var request = new HttpRequestMessage
{
    RequestUri = endpoint,
    Method = httpMethod,
    Content = data
};

var result = string.Empty;
using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
    int read;
    var offset = 0;
    var responseBuffer = new byte[1024];
    do
    {
        read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
        result += Encoding.UTF8.GetString(responseBuffer, 0, read);
        offset += read;
        Console.WriteLine($"Offset: {offset}");
    } while (read != 0);
    response.EnsureSuccessStatusCode();
}
return JsonConvert.DeserializeObject<T>(result);

0 个答案:

没有答案