C#发送HTTP POST请求和响应POST请求

来源:互联网 发布:国美容美发软件下载 编辑:程序博客网 时间:2024/04/28 19:58

发送请求:

private void button1_Click(object sender, EventArgs e)
        {
            string sUrl = txtUrl.Text;
            string sParam = postParam.Text;
            HttpWebRequest req = WebRequest.Create(sUrl) as HttpWebRequest;
            if (req != null)
            {
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(sParam);
                if (postData.Length > 0)
                {
                    req.ContentLength = postData.Length;
                    req.Timeout = 15000;
                    Stream outputStream = req.GetRequestStream();
                    outputStream.Write(postData, 0, postData.Length);
                    outputStream.Flush();
                    outputStream.Close();
                    try
                    {
                        req.GetResponse();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }


响应请求:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    System.IO.Stream s = Request.InputStream;
                    int count = 0;
                    byte[] buffer = new byte[1024];
                    StringBuilder builder = new StringBuilder();
                    while ((count = s.Read(buffer, 0, 1024)) > 0)
                    {
                        builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                    }
                    s.Flush();
                    s.Close();
                    s.Dispose();
                    string PostData = builder.ToString();
                }
                catch (Exception ex)
                { throw ex; }
           }

}    

0 0
原创粉丝点击