- 在整个响应被传回之前,如何访问响应标头?
- 当流到达时如何读取它?
- HttpClient 是接收 http 响应的精细控制的最佳选择吗?
这是一个可以说明我的问题的片段:
using (var response = await _httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead))
{
var streamTask = response.Content.ReadAsStreamAsync();
//how do I check if headers portion has completed?
//Does HttpCompletionOption.ResponseHeadersRead guarantee that?
//pseudocode
while (!(all headers have been received))
//maybe await a Delay here to let Headers get fully populated
access_headers_without_causing_entire_response_to_be_received
//how do I access the response, without causing an await until contents downloaded?
//pseudocode
while (stremTask.Resul.?) //i.e. while something is still streaming
//? what goes here? a chunk-read into a buffer? or line-by-line since it's http?
...
Edit为我澄清另一个灰色地带:
我发现的任何参考文献都有某种阻塞语句,这会导致等待内容到达。我阅读的参考文献通常访问streamTask.Result或内容上的方法或属性,但我不这样做没有足够的知识来排除哪些此类引用是可以的,因为streamTask正在进行中,哪些引用将导致等待直到任务完成。
根据我自己的测试,在您开始阅读内容流之前,内容不会被传输,并且您的调用是正确的Task.Result
是一个阻塞调用,但它的本质是一个同步点。But,它不会阻塞预缓冲整个内容,它只会阻塞直到内容starts来自服务器。
因此,无限流不会无限长时间地阻塞。因此,尝试异步获取流可能被认为是矫枉过正,特别是当您的标头处理操作相对较短时。但如果您愿意,您始终可以在另一个任务处理内容流时处理标头。像这样的事情就可以实现这一点。
static void Main(string[] args)
{
var url = "http://somesite.com/bigdownloadfile.zip";
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, url);
var getTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
Task contentDownloadTask = null;
var continuation = getTask.ContinueWith((t) =>
{
contentDownloadTask = Task.Run(() =>
{
var resultStream = t.Result.Content.ReadAsStreamAsync().Result;
resultStream.CopyTo(File.Create("output.dat"));
});
Console.WriteLine("Got {0} headers", t.Result.Headers.Count());
Console.WriteLine("Blocking after fetching headers, press any key to continue...");
Console.ReadKey(true);
});
continuation.Wait();
contentDownloadTask.Wait();
Console.WriteLine("Finished downloading {0} bytes", new FileInfo("output.dat").Length);
Console.WriteLine("Finished, press any key to exit");
Console.ReadKey(true);
}
请注意,无需检查标头部分是否完整,您已使用HttpCompletionOption.ResponseHeadersRead
选项。这SendAsync
在检索到标头之前,任务不会继续。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)