利用WebRequest发送和获取数据

客户端代码

 发送数据

   private void button2_Click(object sender, EventArgs e)
        {
           string aa=GetWebStream("http://10.16.76.60/web7/Default.aspx", "data=456", "post", 10000);
           MessageBox.Show(aa);
        }


       /// <summary>
        /// WebRequest 发布
        /// </summary>
        /// <param name="url">发布url</param>
        /// <param name="sendtype">发布类型,post get</param>
        /// <returns></returns>
        static public string GetWebStream(string url, string param, string sendtype, int timeout)
        {
            string responseFromServer = "";
            string StatusDescription = "";
            //url = "http://query.szdod.com/";
            try
            {
                byte[] bs = Encoding.ASCII.GetBytes(param);
                // Create a request for the URL.  
                WebRequest request = WebRequest.Create(url);
                //设置超时和发送方式
                request.Timeout = timeout;
                request.Headers.Set("Pragma", "no-cache");
                request.Method = sendtype;
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bs.Length;


                Stream dataStream = request.GetRequestStream();
                dataStream.Write(bs, 0, bs.Length);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                StatusDescription = response.StatusDescription;
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ":" + StatusDescription);
            }
            if (responseFromServer == null)
            {
                responseFromServer = "";
            }
            return responseFromServer;
        }


 

 

 服务器端代码

 

  服务器端是一个网页用来接收数据

protected void Page_Load(object sender, EventArgs e)
    {
  
            if (Request.Form["data"] != null && Request.Form["data"].ToString().Length > 0)
            {
                string lcdata = Request.Form["data"].ToString();
                //对数据进行验证
               
                lcdata = HttpUtility.UrlDecode(Request.Form["lcdata"].ToString(), System.Text.Encoding.UTF8);
              
                //返回给客户端的数据
                Response.Write("中华人民共和国");
         
                Response.End();

            }
    }


 

你可能感兴趣的:(exception,Stream,object,String,服务器,url)