C#实现POST提交方式

网页自动登录和提交POST信息的核心就是分析网页的源代码(HTML),在C#中,可以用来提取网页HTML的组件比较多,常用的用WebBrowser、WebClient、HttpWebRequest这三个。此处使用HttpWebRequest举例,其他两种见参考文章。

private void button1_Click(object sender, EventArgs e)
{
  string postUrl = http://192.168.100.131:8081;
  string postXml ="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
		"<Request id=\"123456\">"+
		"<Param>"+
		"<Item number=\"123456\" />"+
		"</Param>"+
		"</Request>";

  string result = PostWebRequest(postUrl, postXml,Encoding.UTF8);
}

private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
  string ret = string.Empty;
  try
  {
     byte[] byteArray = dataEncode.GetBytes(paramData); //转化
      HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
     webReq.Method = "POST";
     webReq.ContentType = "application/x-www-form-urlencoded";

     webReq.ContentLength = byteArray.Length;
     Stream newStream = webReq.GetRequestStream();
     newStream.Write(byteArray, 0, byteArray.Length);//写入参数
      newStream.Close();
     HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
     StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
     ret = sr.ReadToEnd();
     sr.Close();
     response.Close();
     newStream.Close();
     }
   catch (Exception ex)
   {
     MessageBox.Show(ex.Message);
   }
   return ret;
}



 

参考文章

http://www.cnblogs.com/cgli/archive/2011/04/09/2010497.html

http://www.cnblogs.com/sufei/archive/2011/05/22/2053642.html

 

展开阅读全文

没有更多推荐了,返回首页