如何在不从服务器读取内容的情况下获取`HttpStatusCode`?
How to get the `HttpStatusCode` without reading the content from the server?
我从服务器
检索了一个巨大的JSON
数据
问题是,序列化过程有性能成本,为了最小化这种成本,我需要首先将这些数据作为流检索,然后借助 Newtonsoft 的 Json.net
库 serialize the data as a stream 到所需的类型。
现在我这样做:
using (var stream = await httpClient.GetStreamAsync(requestUrl))
{
using(var streamReader = new StreamReader(stream))
{
using(var jsonReader = new JsonTextReader(streamReader))
{
var items = jsonSerializer.Deserialize<TEntity[]>(jsonReader);
//Some logic
}
}
}
上面的代码很好,但是我需要从响应对象中获取HttpStatusCode
,但是在使用流时无法获取响应对象。我搜索了解决方案并找到了 个问题。
现在,我的问题是:这两种方法有什么区别吗?
调用GetAsync
获取响应对象再调用response.Content.ReadAsStreamAsync
会不会有性能开销?
我的意思是HttpClient
是怎么做到的?
是否加载将数据放入内存,然后当我调用 response.Content.ReadAsStreamAsync
时,我从内存中读取数据作为流?
或者,当我调用 response.Content.ReadAsStreamAsync
时,我直接从中获取数据作为流服务器?
HttpCompletionOption.ResponseHeadersRead
是你的朋友。
The operation should complete as soon as a response is available and headers are read. The content is not read yet.
您可以在一些 HttpClient 方法重载中使用它:
using (HttpResponseMessage response = await client.GetAsync(url,
HttpCompletionOption.ResponseHeadersRead))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
//...
HttpCompletionOption
控制响应是在完全下载后 (ResponseContentRead
) 还是在收到 headers 后立即返回给调用者 (ResponseHeadersRead
),允许流式传输和保存内存资源。
我从服务器
检索了一个巨大的JSON
数据
问题是,序列化过程有性能成本,为了最小化这种成本,我需要首先将这些数据作为流检索,然后借助 Newtonsoft 的 Json.net
库 serialize the data as a stream 到所需的类型。
现在我这样做:
using (var stream = await httpClient.GetStreamAsync(requestUrl))
{
using(var streamReader = new StreamReader(stream))
{
using(var jsonReader = new JsonTextReader(streamReader))
{
var items = jsonSerializer.Deserialize<TEntity[]>(jsonReader);
//Some logic
}
}
}
上面的代码很好,但是我需要从响应对象中获取HttpStatusCode
,但是在使用流时无法获取响应对象。我搜索了解决方案并找到了
现在,我的问题是:这两种方法有什么区别吗?
调用GetAsync
获取响应对象再调用response.Content.ReadAsStreamAsync
会不会有性能开销?
我的意思是HttpClient
是怎么做到的?
是否加载将数据放入内存,然后当我调用 response.Content.ReadAsStreamAsync
时,我从内存中读取数据作为流?
或者,当我调用 response.Content.ReadAsStreamAsync
时,我直接从中获取数据作为流服务器?
HttpCompletionOption.ResponseHeadersRead
是你的朋友。
The operation should complete as soon as a response is available and headers are read. The content is not read yet.
您可以在一些 HttpClient 方法重载中使用它:
using (HttpResponseMessage response = await client.GetAsync(url,
HttpCompletionOption.ResponseHeadersRead))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
//...
HttpCompletionOption
控制响应是在完全下载后 (ResponseContentRead
) 还是在收到 headers 后立即返回给调用者 (ResponseHeadersRead
),允许流式传输和保存内存资源。