The Ash Bot
The Ash Bot

Reputation: 69

Reading Data from the web in chunks using HttpClient C#

I am trying to call the web and receive the data that it sends 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?

Upvotes: 2

Views: 1205

Answers (1)

The Ash Bot
The Ash Bot

Reputation: 69

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

Upvotes: 2

Related Questions