Skip to content

Commit 1de4834

Browse files
committed
Improve HTTP request sample
- The approach there wasn't taking into account situation where the read from the stream was an empty array because the server didn't reply fast enough.
1 parent a40991e commit 1de4834

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

samples/HTTP/HttpWebRequest/Program.cs

+9-2
Original file line numberDiff line numberDiff line change
@@ -88,20 +88,27 @@ public static void Main()
8888

8989
byte[] buffer = new byte[1024];
9090
int bytesRead = 0;
91+
int totalBytesRead = 0;
9192

9293
Debug.WriteLine("Http response follows");
9394
Debug.WriteLine(">>>>>>>>>>>>>");
9495

9596
do
9697
{
9798
bytesRead = stream.Read(buffer, 0, buffer.Length);
98-
Debug.Write(Encoding.UTF8.GetString(buffer, 0, bytesRead));
99+
100+
if (bytesRead > 0)
101+
{
102+
totalBytesRead += bytesRead;
103+
Debug.Write(Encoding.UTF8.GetString(buffer, 0, bytesRead));
104+
}
99105
}
100-
while (bytesRead >= buffer.Length);
106+
while (totalBytesRead < httpWebResponse.ContentLength);
101107
}
102108

103109
Debug.WriteLine(">>>>>>>>>>>>>");
104110
Debug.WriteLine("End of Http response");
111+
Debug.WriteLine($"Read {totalBytesRead} bytes");
105112
}
106113

107114
Thread.Sleep(Timeout.Infinite);

0 commit comments

Comments
 (0)