gpt4 book ai didi

c# - HttpResponseMessage.Content.ReadAsStreamAsync() 与 HttpResponseMessage.Content.ReadAsStringAsync()

转载 作者:行者123 更新时间:2023-12-04 11:30:41 37 4
gpt4 key购买 nike

var request = new HttpRequestMessage(HttpMethod.Get, $"api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

using (var response = await _httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();

using (var streamReader = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(streamReader))
{
var jsonSerializer = new JsonSerializer();
var data = jsonSerializer.Deserialize<Item>(jsonTextReader);
}
}
}
...
var request = new HttpRequestMessage(HttpMethod.Get, "api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Item>>(content);
我已经运行了这两个示例,我很好奇它们总是得到相同结果的区别是什么,ReadAsStreamAsync 比 ReadAsStringAsync 快得多。

最佳答案

在引擎盖下,HttpClient将内容存储在 MemoryStream .所以,基本上叫 ReadAsStreamAsync只返回对流的引用。拨打ReadAsStringAsync的情况下, ToArray方法在内存流上被调用,因此创建了一个额外的数据副本。

关于c# - HttpResponseMessage.Content.ReadAsStreamAsync() 与 HttpResponseMessage.Content.ReadAsStringAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62563636/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com