zoukankan      html  css  js  c++  java
  • HttpWebRequest和HttpWebResponse实例

    关于HttpWebRequest详细用法可以参考MSDN和我的另一篇
    这个例子只是一个客户端发起请求,服务端简单处理相应的例子。

    客户端请求

                string reqestMsg = "Tom";
                string responseMsg = string.Empty;
                byte[] buffer = Encoding.UTF8.GetBytes(reqestMsg);
    
                try
                {
          //把请求地址换成博客园的 如http://www.cnblogs.com 就返回了整个页面数据  
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:6603/WebServer.aspx");
                    request.Method = "POST";
                    request.ContentLength = buffer.Length;
    
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(buffer, 0, buffer.Length);
                    }
    
                    HttpWebResponse resonse = (HttpWebResponse)request.GetResponse();
                    Stream responseStream = resonse.GetResponseStream();
                    
                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        responseMsg = sr.ReadToEnd();
                    }
    
                    resonse.Close();
                }
                catch (Exception ex)
                {
                    responseMsg = ex.Message;
                }
    
                Response.Write(responseMsg);
    

    服务端相应

                string responseMsg = "NO MSG";
    
                if (Request.InputStream != null)
                {
                    byte[] buffer = new byte[Request.InputStream.Length];
                    Request.InputStream.Read(buffer, 0, buffer.Length);
                    string msg = Encoding.UTF8.GetString(buffer);
                    msg = msg.Replace("+", "%2B").Replace(" ", "%20");
                    responseMsg = SayHello(msg);
                }
    
                Response.Write(responseMsg);
    
  • 相关阅读:
    8.耍杂技的牛 推公式
    内联函数分析
    类的静态成员变量
    操作符重载的概念
    数组本质分析
    动态内存分配
    函数重载分析
    指针本质分析
    单引号和双引号
    内存操作经典问题分析
  • 原文地址:https://www.cnblogs.com/xqhppt/p/2503546.html
Copyright © 2011-2022 走看看