WebRequest 對象的使用

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   使用   for   資料   

 

 

// 待請求的地址string url = "http://www.cnblogs.com";             // 建立 WebRequest 對象,WebRequest 是抽象類別,定義了請求的規定,// 可以用於各種請求,例如:Http, Ftp 等等。// HttpWebRequest 是 WebRequest 的衍生類別,專門用於 HttpSystem.Net.HttpWebRequest request    = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest; // 請求的方式通過 Method 屬性設定 ,預設為 GET// 可以將 Method 屬性設定為任何 HTTP 1.1 協議謂詞:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。request.Method = "POST"; // 還可以在請求中附帶 Cookie// 但是,必須首先建立 Cookie 容器request.CookieContainer = new System.Net.CookieContainer(); System.Net.Cookie requestCookie    = new System.Net.Cookie("Request", "RequestValue","/", "localhost");request.CookieContainer.Add(requestCookie); Console.WriteLine("請輸入請求參數:"); // 輸入 POST 的資料.string inputData = Console.ReadLine(); // 拼接成請求參數串,並進行編碼,成為位元組string postData = "firstone=" + inputData;ASCIIEncoding encoding = new ASCIIEncoding();byte[] byte1 = encoding.GetBytes(postData); // 佈建要求的參數形式request.ContentType = "application/x-www-form-urlencoded"; // 佈建要求參數的長度.request.ContentLength = byte1.Length; // 取得發向伺服器的流System.IO.Stream newStream = request.GetRequestStream(); // 使用 POST 方法請求的時候,實際的參數通過請求的 Body 部分以流的形式傳送newStream.Write(byte1, 0, byte1.Length); // 完成後,關閉請求流.newStream.Close(); // GetResponse 方法才真的發送請求,等待伺服器返回System.Net.HttpWebResponse response    = (System.Net.HttpWebResponse)request.GetResponse(); // 首先得到回應的頭部,可以知道返回內容的長度或者類型Console.WriteLine("Content length is {0}", response.ContentLength);Console.WriteLine("Content type is {0}", response.ContentType); // 回應的 Cookie 在 Cookie 容器中foreach (System.Net.Cookie cookie in response.Cookies){    Console.WriteLine("Name: {0}, Value: {1}", cookie.Name, cookie.Value);}Console.WriteLine(); // 然後可以得到以流的形式表示的回應內容System.IO.Stream receiveStream     = response.GetResponseStream();      // 還可以將位元組流封裝為進階的字元流,以便於讀取常值內容 // 需要注意編碼System.IO.StreamReader readStream     = new System.IO.StreamReader(receiveStream, Encoding.UTF8); Console.WriteLine("Response stream received.");Console.WriteLine(readStream.ReadToEnd()); // 完成後要關閉字元流,字元流底層的位元組流將會自動關閉response.Close();readStream.Close();

 

WebRequest 對象的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.