天天看點

使用 HttpRequester 更友善的發起 HTTP 請求使用 HttpRequester 更友善的發起 HTTP 請求

使用 HttpRequester 更友善的發起 HTTP 請求

Intro #

一直感覺 .net 裡面(這裡主要說的是 .net framework 下)發送 HTTP 請求的方式用着不是特别好用,而且在 .net framework 裡發送 HTTP 請求的方式有好幾種,如:

WebClient

/

WebRequest

HttpClient

,于是自己封裝了一個 HttpRequester

WebClient

 主要是用來下載下傳,不能對 HTTP 做較多的自定義,

HttpClient

 是微軟後來加入的,也是比較推薦使用的處理 HTTP 請求的,但是在 .net framework 下如果不注意的話可能會造成很大的災難,從 .net core 2.1 開始,微軟引入了 

HttpClientFactory

 去解決了一些問題,如果你是在 .net core 程式下跑的話,推薦使用 

HttpClient

,如果在 .net framework 下跑的話可以使用 

WebRequest

,這裡說明一下,.net core 下,

WebRequest

 内部也是基于 

HttpClient

 的,詳細可以參考 

https://github.com/dotnet/corefx/blob/master/src/System.Net.Requests/src/System/Net/HttpWebRequest.cs#L1096

HttpRequester

 是基于 

WebRequest

 封裝的,使用比較簡潔的 Fluent API 的方式調用,如果是在 .net framework 下開發,可以嘗試使用一下,具體使用可以參考下面的示例以及 Github 上的

示例代碼 示例代碼2

添加 Nuget 包引用

添加對 

WeihanLi.Common

 的引用,需要 1.0.14 及以上版本

使用 

HttpRequester

Copy

var result = new HttpRequester("https://weihanli.xyz") // 使用 GET 方式請求 https://weihanli.xyz .Execute(); // 傳回 responseText System.Console.WriteLine(result); // 使用 POST 方法請求 https://accounting.weihanli.xyz/Account/LogOn var loginResult = new HttpRequester("https://accounting.weihanli.xyz/Account/LogOn", HttpMethod.Post) .WithHeaders(new Dictionary<string, string>() { { "X-Requested-With", "XMLHttpRequest" }, }) // 設定請求頭 // .AjaxRequest(true) // 設定 Referer,在做爬蟲時會比較有用,還可以通過 WithProxy("proxyUrl") 設定代理 .WithReferer("https://accounting.weihanli.xyz/Account/Login?ReturnUrl=%2F") // 手動設定 UserAgent,預設會随機設定一個 UA .WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36") .WithFormParameters(new Dictionary<string, string>() { {"Username","liweihan" }, {"Password", "112233" }, {"RememberMe","false" } }) // 設定 post 的 form 參數 // 擷取傳回的 responseText,并 json 反序列化為一個強類型的Model .Execute<WeihanLi.Common.Models.JsonResultModel<bool>>(); System.Console.WriteLine(loginResult.ToJson()); // 上傳檔案示例 var uploadFileResponse = new HttpRequester("https://graph.baidu.com/upload", HttpMethod.Post) .WithFile($@"{System.Environment.GetEnvironmentVariable("USERPROFILE")}\Pictures\4e6ab53e383863ed4d15252039f70423.jpg", "image", new Dictionary<string, string>() { { "tn","pc" }, { "from","pc" }, { "image_source","PC_UPLOAD_SEARCH_FILE" }, { "range","{\"page_from\": \"searchIndex\"}" }, }) // 設定上傳檔案,并設定其它 form 參數資訊 .WithReferer("https://baidu.com/") // 設定 referer .WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36") .ExecuteForResponse(); // 擷取一個 HttpWebResponse 對象,可以使用 StatusCode/ ResponseHeader 等資訊 System.Console.WriteLine($"Response status:{uploadFileResponse.StatusCode}, result:{uploadFileResponse.ReadToEnd()}");

More

除了 Header/Referer/UserAgent 之外,還可以設定 Proxy,設定 Cookie,Ajax 請求 等資訊,而且還可以直接 PostJson 示例如下:

new HttpRequester("requestUrl", HttpMethod.Post) .WithProxy("proxyUrl") // 使用代理 //.WithProxy("url", "userName", "password") // 配置帶密碼的代理 .WithCookie(cookie) //帶 Cookie 通路 //.WithCookie("url", cookie) // 隻用指定路徑的 cookie .WithJsonParameter(entity) // post 一個 json 對象,content-type 會自動設定為 `application/json` .AjaxRequest(true) // 設定該請求是 Ajax 請求 .Execute();

Memo

歡迎體驗~,如果有什麼問題或者發現什麼 bug 歡迎和我聯系或者給我

提 issue

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

原文位址

https://www.cnblogs.com/weihanli/p/fire-http-request-with-http-requester.html