如何在WinForm中發送HTTP請求


如何在WinForm中請求發送HTTP

手工發送HTTP請求主要是調用 System.Net的HttpWebResponse方法

手工發送HTTP的GET請 求:

string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword=";
strURL +=this.textBox1.Text;
System.Net.HttpWebRequest request;
// 創建一個HTTP請求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//request.Method="get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
XmlTextReader Reader = new XmlTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXml();
strValue = strValue.Replace("&lt;","<");
strValue = strValue.Replace("&gt;",">");
MessageBox.Show(strValue); 
Reader.Close();
/* 何問起 hovertree.com */

手工發送HTTP的POST請求

string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch";
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("keyword");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(this.textBox1.Text);
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.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();
string strValue = Reader.ReadInnerXml();
strValue = strValue.Replace("&lt;","<");
strValue = strValue.Replace("&gt;",">");
MessageBox.Show(strValue); 
Reader.Close();
/* 何問起 hovertree.com */

轉自:http://hovertree.com/h/bjaf/i7cux0g6.htm

推薦:http://www.cnblogs.com/roucheng/p/3521864.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM