.net提供的5種request-response方法一

來源:互聯網
上載者:User

標籤:blog   http   io   ar   檔案   art   div   sp   cti   

     .net提供了三種基本方法和兩種底層方法來發送http請求和接收http響應,通過這些方法,我們可以模仿在瀏覽器地址欄輸入URL地址訪問網頁的方法。我們發送http請求,接收伺服器返回的響應(通常就是HTML網頁)。由此對得到的網頁進行分析,比如做自動化測試、或者抓取該網頁上你感興趣的東西,再放到自己程式裡,總之應用很多,我能想到的,暫時就這麼多。

五種方法分別是:

1.WebClient

2.WebRequest-WebResponse

3.HttpWebRequest-HttpWebResponse

4.TcpClient

5.Socket

其中前三種比較簡單,後兩者比較底層

 

本文先寫第一種WebClient,比較簡單,直接上代碼

C#代碼  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net;  
  6.   
  7. namespace WebClientTest  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             string uri="http://starnc.iteye.com/blog/404768";  
  14.             WebClient wc=new WebClient();  
  15.             Console.WriteLine("Sending an http Get request to"+uri);  
  16.             byte[] bResponse=wc.DownloadData(uri);  
  17.             string strResponse=Encoding.UTF8.GetString(bResponse);  
  18.             Console.WriteLine("HTTP response is: ");  
  19.             Console.WriteLine(strResponse);  
  20.         }  
  21.     }  
  22. }  

 得到結果如

 



 

 

這就是我們得到的網頁源檔案,和你直接在IE裡訪問那個URL的網頁得到的結果是一樣的,有了這個你可以幹你喜歡乾的事了。

 

 

本文參考了《.net軟體自動化測試之道》,一本不錯的書,大家應該看看。

.net提供的5種request-response方法一

聯繫我們

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