使用 HttpClient C# 从网络上分块读取数据

问题描述 投票:0回答:1

我正在尝试调用网络并接收它分块发回的数据。换句话说,我正在尝试从网络接收并打印它,同时还会有更多数据进入。但我找不到任何包含代码示例的内容。我能找到的内容是将 HttpCompletionOption 传递到 httpClient.SendAsync 函数中,但我不知道之后要做什么。

这是我目前拥有的代码:

using (HttpClient httpClient = new HttpClient())
{
    using (HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), url))
    {
        string content = "{ \"exampleJson\": \"This is an example\" }";

        request.Content = new StringContent(content);

        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        HttpResponseMessage httpResponse = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);

        httpResponse.EnsureSuccessStatusCode();

        // But what do I do to get the json data as it is coming in from the web?

        return;

    }
}

但是现在我该怎么做才能从网络获取 JSON 数据呢?

web httpclient dotnet-httpclient chunks data-stream
1个回答
0
投票

我找到了我需要做的事情。我替换了这段代码

// But what do I do to get the json data as it is coming in from the web?

使用这个新代码

// Check if the response is successful
if (httpResponse.IsSuccessStatusCode)
{
    string responseString = "";
    // Read the response data in chunks
    using (Stream responseStream = await httpResponse.Content.ReadAsStreamAsync())
    {
        using (StreamReader reader = new StreamReader(responseStream))
        {
            char[] buffer = new char[4096];
            int bytesRead;
            while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                responseString += new string(buffer, 0, bytesRead);
                Console.WriteLine(responseString);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.