標籤: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#代碼
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
-
- namespace WebClientTest
- {
- class Program
- {
- static void Main(string[] args)
- {
- string uri="http://starnc.iteye.com/blog/404768";
- WebClient wc=new WebClient();
- Console.WriteLine("Sending an http Get request to"+uri);
- byte[] bResponse=wc.DownloadData(uri);
- string strResponse=Encoding.UTF8.GetString(bResponse);
- Console.WriteLine("HTTP response is: ");
- Console.WriteLine(strResponse);
- }
- }
- }
得到結果如
這就是我們得到的網頁源檔案,和你直接在IE裡訪問那個URL的網頁得到的結果是一樣的,有了這個你可以幹你喜歡乾的事了。
本文參考了《.net軟體自動化測試之道》,一本不錯的書,大家應該看看。
.net提供的5種request-response方法一