C#发送Post方式的Http请求

  • Post author:
  • Post category:其他


具体代码:

string strURL = "http://xxxxxxxxxx";
            try
            {
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";
                // 参数经过URL编码,此处共三个编码
                string paraUrlCoded = System.Web.HttpUtility.UrlEncode("action");
                paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("vote");
                paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("cid");
                paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("18");
                paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("voteId[]");
                paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("258");
                paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("Submit");
                paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("");

                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请求流
                Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Dispose();
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;

                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
//进行接收,(省略会造成程序无响应)。
                s = response.GetResponseStream();
                XmlTextReader Reader = new XmlTextReader(s);
                Reader.MoveToContent();
                Reader.Close(); 
            }



版权声明:本文为Devil_SKY_TH原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。