在WinForm中發(fā)送HTTP請求的實現(xiàn)方法
更新時間:2016年06月07日 10:51:00 投稿:jingxian
下面小編就為大家?guī)硪黄赪inForm中發(fā)送HTTP請求的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
如何在WinForm中請求發(fā)送HTTP
手工發(fā)送HTTP請求主要是調(diào)用 System.Net的HttpWebResponse方法
手工發(fā)送HTTP的GET請求:
string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword=";
strURL +=this.textBox1.Text;
System.Net.HttpWebRequest request;
// 創(chuàng)建一個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("<","<");
strValue = strValue.Replace(">",">");
MessageBox.Show(strValue);
Reader.Close();
手工發(fā)送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";
// 內(nèi)容類型
request.ContentType="application/x-www-form-urlencoded";
// 參數(shù)經(jīng)過URL編碼
string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(this.textBox1.Text);
byte[] payload;
//將URL編碼后的字符串轉(zhuǎn)化為字節(jié)
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//設(shè)置請求的 ContentLength
request.ContentLength = payload.Length;
//獲得請 求流
Stream writer = request.GetRequestStream();
//將請求參數(shù)寫入流
writer.Write(payload,0,payload.Length);
// 關(guān)閉請求流
writer.Close();
System.Net.HttpWebResponse response;
// 獲得響應(yīng)流
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("<","<");
strValue = strValue.Replace(">",">");
MessageBox.Show(strValue);
Reader.Close();
以上這篇在WinForm中發(fā)送HTTP請求的實現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:

