新建一个.NET Core控制台项目,代码如下所示:
using System; using System.Text; using System.Net; using System.Collections.Generic; namespace NetCoreWebRequest { class Program { static void Main(string[] args) { HttpWebRequest httpWebRequest = WebRequest.Create("http://www.baidu.com") as HttpWebRequest; httpWebRequest.Method = "POST"; using (var requestStream = httpWebRequest.GetRequestStream()) { byte[] data = Encoding.UTF8.GetBytes("Hello"); requestStream.Write(data, 0, data.Length); requestStream.Flush(); } using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse) { using (var responseStream = response.GetResponseStream()) { byte[] readBuffer = new byte[1000]; List<byte> allData = new List<byte>(); int readBytes; do { readBytes = responseStream.Read(readBuffer, 0, readBuffer.Length); for (var i = 0; i < readBytes; i++) { allData.Add(readBuffer[i]); } } while (readBytes > 0);//如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕 string message = Encoding.UTF8.GetString(allData.ToArray()); Console.WriteLine(message); } } Console.WriteLine("Press key to end..."); Console.ReadKey(); } } }
注意本文阐述的重点是,上面代码中,如果responseStream.Read(readBuffer, 0, readBuffer.Length)返回的值readBytes为 0了,表示HttpWebResponse中的所有数据已经被读取完毕了。