zoukankan      html  css  js  c++  java
  • C#使用HttpWebRequest发送数据和使用HttpWebResponse接收数据的一个简单示例

    新建一个.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中的所有数据已经被读取完毕了。

  • 相关阅读:
    Java中的阻塞队列
    大数据笔记
    物联网小笔记
    shell 笔记
    Redis笔记
    rabbitMQ笔记
    java.lang.NoClassDefFoundError: freemarker/template/Template
    分布式系列学习-事务处理
    免费无需破解xshell xftp下载
    idea maven模块变灰或者java文件夹非 Sources文件夹
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/11350397.html
Copyright © 2011-2022 走看看