本篇博客對應視頻講解html
上一篇講了Linq的使用,你們本身上手實踐以後,相信必定會感到很是快捷方便。更多詳細的內容仍是須要本身去閱讀官方文檔。 今天要講網絡請求中的http請求,這也是在編程當中常常使用到的內容之一。web
關於Http是什麼,請求類型這些內容我在此都不說了,須要你們本身閱讀相關資料。一般來說,咱們在進行數據採集,API調用,模擬登陸等功能開發的時候,免不了使用http請求。 即便用瀏覽器能作到的事情,咱們均可以經過編程去實現。畢竟瀏覽器自己也是一種應用程序,也是編程的產出結果。 關於.Net 平臺提供的網絡編程相關內容,你們能夠閱讀官方文檔。編程
進行網絡請求,對於通常的需求,咱們使用HttpClient
與WebClient
類便可。WebClient
進行了更高級的封裝,更容易使用,同時也意味着更少的自定義,更低的靈活性。 一般咱們進行網絡請求要進行相關的步驟:瀏覽器
咱們經過實際的例子來講明:網絡
// webclient 的簡單使用 using (var wc = new WebClient()) { // 設置編碼 wc.Encoding = Encoding.UTF8; // 請求內容 var result = wc.DownloadString("https://www.baidu.com"); // 保存到文件 File.WriteAllText("baidu.html", result); }
HttpConent
類)做爲請求內容的容器。// httpClient 請求 using (var hc = new HttpClient()) { string result = ""; var httpResponse = new HttpResponseMessage(); // get請求 httpResponse = hc.GetAsync("https://www.baidu.com").Result; result = httpResponse.Content.ReadAsStringAsync().Result; Console.WriteLine(result); // post請求,構造不一樣類型的請求內容 var data = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("from","msdev.cc"), }; // 封閉成請求結構體 var content = new FormUrlEncodedContent(data); // 進行請求,獲取返回數據 httpResponse = hc.PostAsync("https://msdev.cc", content).Result; // 將返回數據做爲字符串 result = httpResponse.Content.ReadAsStringAsync().Result; File.WriteAllText("post.html", result); } // 自定義請求及結果處理 using (var hc = new HttpClient()) { string result = ""; var httpRequest = new HttpRequestMessage(); var httpResponse = new HttpResponseMessage(); // 請求方法 httpRequest.Method = HttpMethod.Put; // 請求地址 httpRequest.RequestUri = new Uri("https://msdev.cc"); // 請求內容 httpRequest.Content = new StringContent("request content"); // 設置請求頭內容 httpRequest.Headers.TryAddWithoutValidation("", ""); // 設置超時 hc.Timeout = TimeSpan.FromSeconds(5); // 獲取請求結果 httpResponse = hc.SendAsync(httpRequest).Result; // 判斷請求結果 if (httpResponse.StatusCode == HttpStatusCode.OK) { result = httpResponse.Content.ReadAsStringAsync().Result; File.WriteAllText("custom.html", result); } else { Console.WriteLine(httpResponse.StatusCode + httpResponse.RequestMessage.ToString()); } }