|
手工發(fā)送HTTP請(qǐng)求主要是調(diào)用System.Net的HttpWebResponse方法
手工發(fā)送HTTP的GET請(qǐng)求: string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword="; strURL +=this.textBox1.Text; System.Net.HttpWebRequest request; //創(chuàng)建一個(gè)HTTP請(qǐng)求 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請(qǐng)求 string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch"; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); //Post請(qǐng)求方式 request.Method="POST"; //內(nèi)容類型 request.ContentType="application/x-www-form-urlencoded"; //參數(shù)經(jīng)過(guò)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è)置請(qǐng)求的ContentLength request.ContentLength = payload.Length; //獲得請(qǐng)求流 Stream writer = request.GetRequestStream(); //將請(qǐng)求參數(shù)寫入流 writer.Write(payload,0,payload.Length); //關(guān)閉請(qǐng)求流 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(); Get請(qǐng)求與Post請(qǐng)求的主要區(qū)別在于Post的參數(shù)要經(jīng)過(guò)URL編碼并在獲得請(qǐng)求之前傳送,而Get把參數(shù)用URL編碼后直接附加到請(qǐng)求的URL后面 URL編碼是一種字符編碼格式,它確保傳遞的參數(shù)由一致的文本組成(如將空格編碼為"%20") url傳遞中文的解決辦法:
HTTP請(qǐng)求返回的狀態(tài)碼說(shuō)明
相關(guān)鏈接:
http://topic.csdn.net/t/20050220/01/3792701.html winform 向網(wǎng)頁(yè)傳遞數(shù)據(jù) 用來(lái)發(fā)送http請(qǐng)求和獲取回發(fā)數(shù)據(jù)
可以保存登錄session。
|
|
|
來(lái)自: 青格兒 > 《軟件開發(fā)》