(SOLVED) 使用 HttpClient 在 C# 中以块的方式从网络读取数据

huangapple go评论63阅读模式
英文:

(SOLVED) Reading Data from the web in chunks using HttpClient C#

问题

我试图调用网络并以块的形式接收它发送的数据。换句话说,我正在尝试在数据不断到来时从网络接收并打印它,但我找不到包含示例代码的内容。根据我找到的信息,建议在httpClient.SendAsync函数中传递HttpCompletionOption,但之后我不知道该怎么做。

这是我目前的代码:

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();

        // 但我该如何在数据从网络中不断到来时获取JSON数据?

        return;
    }
}

但现在,我该如何在数据从网络中不断到来时获取JSON数据?任何帮助将不胜感激。

英文:

I am trying to call the web and receive the data that it send back in chunks. So in other words I am trying to receive from the web and print it, while more data is coming in. But I can not find anything that has code examples in it. What I can find says to pass HttpCompletionOption into the httpClient.SendAsync function but I have no clue what to do after that.

Here is the code that I currently have:

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;

    }
}

But now what do I do to get the json data from the web as it is coming in? Any help would be vary appreciated.

答案1

得分: 0

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

// 检查响应是否成功
if (httpResponse.IsSuccessStatusCode)
{
    string responseString = "";
    // 以块的方式读取响应数据
    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);
            }
        }
    }
}

希望这对你有所帮助!

英文:

I found what I needed to do. I replaced this code

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

with this new code

// 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);
            }
        }
    }
}

I hope this helps you!

huangapple
  • 本文由 发表于 2023年6月8日 03:20:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定