1. 程式人生 > >網絡請求HttpWebRequest的Get和Post

網絡請求HttpWebRequest的Get和Post

toe 應對 sts 引用 style eat == .aspx web

用下邊的小例子講解具體功能的實現:
首先,我們想要請求遠程站點,需要用到HttpWebRequest類,該類在System.Net命名空間中,所以需要引用一下。另外,在向請求的頁面寫入參數時需要用到Stream流操作,所以需要引用System.IO命名空間
以下為Get請求方式:

  • Uri uri = new Uri("http://www.cnsaiko.com/");//創建uri對象,指定要請求到的地址
  • if (uri.Scheme.Equals(Uri.UriSchemeHttp))//驗證uri是否以http協議訪問
  • {
  • HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);//使用HttpWebRequest類的Create方法創建一個請求到uri的對象。

  • request.Method = WebRequestMethods.Http.Get;//指定請求的方式為Get方式

  • HttpWebResponse response = (HttpWebResponse)request.GetResponse();//獲取該請求所響應回來的資源,並強轉為HttpWebResponse響應對象
  • StreamReader reader = new StreamReader(response.GetResponseStream());//獲取該響應對象的可讀流

  • string str = reader.ReadToEnd(); //將流文本讀取完成並賦值給str

  • response.Close(); //關閉響應
  • Response.Write(str); //本頁面輸出得到的文本內容
  • Response.End(); //本頁面響應結束。
  • }

以下為POST請求方式:

    • Uri uri = new Uri("http://www.cnsaiko.com/Admin/Login.aspx?type=Login");//創建uri對象,指定要請求到的地址,註意請求的地址為form表單的action地址。

    • if (uri.Scheme == Uri.UriSchemeHttp)//驗證uri是否以http協議訪問
    • {

    • string name = Server.UrlEncode("張三");//將要傳的參數進行url編碼

    • string pwd = Server.UrlEncode("123");

    • string data = "UserName=" + name + "&UserPwd=" + pwd; //data為要傳的參數,=號前邊的為表單元素的名稱,後邊的為要賦的值;如果參數為多個,則使用"&"連接。
    • HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
    • request.Method = WebRequestMethods.Http.Post;//指定請求的方式為Post方式
    • request.ContentLength = data.Length; //指定要請求參數的長度
    • request.ContentType = "application/x-www-form-urlencoded"; //指定請求的內容類型

    • StreamWriter writer = new StreamWriter(request.GetRequestStream()); //用請求對象創建請求的寫入流
    • writer.Write(data); //將請求的參數列表寫入到請求對象中
    • writer.Close(); //關閉寫入流。

    • HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    • StreamReader reader = new StreamReader(response.GetResponseStream());

    • string str = reader.ReadToEnd();
    • response.Close();
    • Response.Write(str);
    • Response.End();
    • }

網絡請求HttpWebRequest的Get和Post