如何在WinForm中發送HTTP請求

來源:互聯網
上載者:User

標籤:winform   style   class   blog   code   http   

Winform表單中發送HTTP請求


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

手工發送HTTP的GET請 求:

 1 string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword="; 2 strURL +=this.textBox1.Text; 3 System.Net.HttpWebRequest request; 4 // 建立一個HTTP請求 5 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); 6 //request.Method="get"; 7 System.Net.HttpWebResponse response; 8 response = (System.Net.HttpWebResponse)request.GetResponse(); 9 System.IO.Stream s;10 s = response.GetResponseStream();11 XmlTextReader Reader = new XmlTextReader(s);12 Reader.MoveToContent();13 string strValue = Reader.ReadInnerXml();14 strValue = strValue.Replace("&lt;","<");15 strValue = strValue.Replace("&gt;",">");16 MessageBox.Show(strValue); 17 Reader.Close();

 

手工發送HTTP的POST請求

 1 string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch"; 2 System.Net.HttpWebRequest request; 3  4 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); 5 //Post請求方式 6 request.Method="POST"; 7 // 內容類型 8 request.ContentType="application/x-www-form-urlencoded"; 9 // 參數經過URL編碼10 string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");11 paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(this.textBox1.Text);12 byte[] payload;13 //將URL編碼後的字串轉化為位元組14 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);15 //佈建要求的 ContentLength 16 request.ContentLength = payload.Length;17 //獲得請 求流18 Stream writer = request.GetRequestStream();19 //將請求參數寫入流20 writer.Write(payload,0,payload.Length);21 // 關閉請求流22 writer.Close();23 System.Net.HttpWebResponse response;24 // 獲得響應流25 response = (System.Net.HttpWebResponse)request.GetResponse();26 System.IO.Stream s;27 s = response.GetResponseStream();28 XmlTextReader Reader = new XmlTextReader(s);29 Reader.MoveToContent();30 string strValue = Reader.ReadInnerXml();31 strValue = strValue.Replace("&lt;","<");32 strValue = strValue.Replace("&gt;",">");33 MessageBox.Show(strValue); 34 Reader.Close(); 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.