1.WebRequest和HttpWebRequest
WebRequest 的命名空間是: System.Net ,它是HttpWebRequest的抽象父類(還有其他子類如FileWebRequest ,FtpWebRequest),WebRequest的子類都用於從web獲取資源。HttpWebRequest利用HTTP 協議和服務器交互,通常是通過 GET 和 POST 兩種方式來對數據進行獲取和提交
一個栗子:
static void Main(string[] args) { // 創建一個WebRequest實例(默認get方式) HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com"); //可以指定請求的類型 //request.Method = "POST"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Console.WriteLine(response.StatusDescription); // 接收數據 Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); // 關閉stream和response reader.Close(); dataStream.Close(); response.Close(); }
運行后輸出百度網頁的html字符串,如下:
2.HttpRequest
- HttpRequest類的命名空間是: System.Web,它是一個密封類,其作用是讓服務端讀取客戶端發送的請求,我們最熟悉的HttpRequest的實例應該是WebForm中Page類的屬性Request了,我們可以輕松地從Request屬性的QueryString,Form,Cookies集合獲取數據中,也可以通過Request["Key"]獲取自定義數據,一個栗子:
protected void Page_Load(object sender, EventArgs e) { //從Request中獲取商品Id string rawId = Request["ProductID"]; int productId; if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId)) { //把商品放入購物車 using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions()) { usersShoppingCart.AddToCart(productId); } } else { throw new Exception("Tried to call AddToCart.aspx without setting a ProductId."); } //跳轉到購物車頁面 Response.Redirect("ShoppingCart.aspx"); }
3.WebClient
命名空間是System.Net,WebClient很輕量級的訪問Internet資源的類,在指定uri后可以發送和接受數據。WebClient提供了 DownLoadData,DownLoadFile,UploadData,UploadFile 方法,同時通過了這些方法對應的異步方法,通過WebClient我們可以很方便地上傳和下載文件。
簡單使用:
static void Main(string[] args) { WebClient wc = new WebClient(); wc.BaseAddress = "http://www.baidu.com/"; //設置根目錄 wc.Encoding = Encoding.UTF8; //設置按照何種編碼訪問,如果不加此行,獲取到的字符串中文將是亂碼 string str = wc.DownloadString("/"); //字符串形式返回資源 Console.WriteLine(str); //----------------------以下為OpenRead()以流的方式讀取---------------------- wc.Headers.Add("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); wc.Headers.Add("Accept-Language", "zh-cn"); wc.Headers.Add("UA-CPU", "x86"); //wc.Headers.Add("Accept-Encoding","gzip, deflate"); //因為我們的程序無法進行gzip解碼所以如果這樣請求獲得的資源可能無法解碼。當然我們可以給程序加入gzip處理的模塊 那是題外話了。 wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); //Headers 用於添加添加請求的頭信息 Stream objStream = wc.OpenRead("?tn=98050039_dg&ch=1"); //獲取訪問流 StreamReader _read = new StreamReader(objStream, Encoding.UTF8); //新建一個讀取流,用指定的編碼讀取,此處是utf-8 Console.Write(_read.ReadToEnd()); //輸出讀取到的字符串 //------------------------DownloadFile下載文件------------------------------- wc.DownloadFile("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.jpg", @"D:\123.jpg"); //將遠程文件保存到本地
//------------------------DownloadFile下載到字節數組-------------------------------
byte[] bytes = wc.DownloadData("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
FileStream fs = new FileStream(@"E:\123.gif", FileMode.Create);
fs.Write(bytes, 0, bytes.Length); fs.Flush();
WebHeaderCollection whc = wc.ResponseHeaders;
//獲取響應頭信息
foreach (string s in whc) {
Console.WriteLine(s + ":" + whc.Get(s));
}
Console.ReadKey();
}
一個使用WebClient下載文件的栗子:
static void Main(string[] args) { WebClient wc = new WebClient(); //直接下載 Console.WriteLine("直接下載開始。。。"); wc.DownloadFile("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx", @"D:\ku.xlsx"); Console.WriteLine("直接下載完成!!!"); //下載完成后輸出 下載完成了嗎? //異步下載 wc.DownloadFileAsync(new Uri("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx"), @"D:\ku.xlsx"); wc.DownloadFileCompleted += DownCompletedEventHandler; Console.WriteLine("do something else..."); Console.ReadKey(); } public static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e) { Console.WriteLine("異步下載完成!"); }
4.HttpClient
HttpClient是.NET4.5引入的一個HTTP客戶端庫,其命名空間為 System.Net.Http 。.NET 4.5之前我們可能使用WebClient和HttpWebRequest來達到相同目的。HttpClient利用了最新的面向任務模式,使得處理異步請求非常容易。
下邊是一個使用控制台程序異步請求接口的栗子:
static void Main(string[] args) { const string GetUrl = "http://xxxxxxx/api/UserInfo/GetUserInfos";//查詢用戶列表的接口,Get方式訪問 const string PostUrl = "http://xxxxxxx/api/UserInfo/AddUserInfo";//添加用戶的接口,Post方式訪問 //使用Get請求 GetFunc(GetUrl); UserInfo user = new UserInfo { Name = "jack", Age = 23 }; string userStr = JsonHelper.SerializeObject(user);//序列化 //使用Post請求 PostFunc(PostUrl, userStr); Console.ReadLine(); } /// <summary> /// Get請求 /// </summary> /// <param name="path"></param> static async void GetFunc(string path) { //消息處理程序 HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; HttpClient httpClient = new HttpClient(); //異步get請求 HttpResponseMessage response = await httpClient.GetAsync(path); //確保響應正常,如果響應不正常EnsureSuccessStatusCode()方法會拋出異常 response.EnsureSuccessStatusCode(); //異步讀取數據,格式為String string resultStr = await response.Content.ReadAsStringAsync(); Console.WriteLine(resultStr); } /// <summary> /// Post請求 /// </summary> /// <param name="path"></param> /// <param name="data"></param> static async void PostFunc(string path, string data) { HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; HttpClient httpClient = new HttpClient(handler); //HttpContent是HTTP實體正文和內容標頭的基類。 HttpContent httpContent = new StringContent(data, Encoding.UTF8, "text/json"); //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BasicAuth", Ticket);//驗證請求頭賦值 //httpContent.Headers.Add(string name,string value) //添加自定義請求頭 //發送異步Post請求 HttpResponseMessage response = await httpClient.PostAsync(path, httpContent); response.EnsureSuccessStatusCode(); string resultStr = await response.Content.ReadAsStringAsync(); Console.WriteLine(resultStr); } }
注意:因為HttpClient有預熱機制,第一次進行訪問時比較慢,所以我們最好不要用到HttpClient就new一個出來,應該使用單例或其他方式獲取HttpClient的實例。上邊的栗子為了演示方便直接new的HttpClient實例。
HttpClient還有很多其他功能,如附帶Cookie,請求攔截等,可以參考https://www.cnblogs.com/wywnet/p/httpclient.html
參考文章:
1.https://www.cnblogs.com/wywnet/p/httpclient.html
2.https://www.cnblogs.com/kissdodog/archive/2013/02/19/2917004.html