Dot-Net
如何用 HttpClient 替換 WebClient?
我的 asp.net mvc Web 應用程序中有以下 WebClient:
using (WebClient wc = new WebClient()) // call the Third Party API to get the account id { string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken; var json = await wc.DownloadStringTaskAsync(url); }那麼任何人都可以建議我如何將它從 WebClient 更改為 HttpClient 嗎?
您可以編寫以下程式碼:
string url = 'some url'; // best practice to create one HttpClient per Application and inject it HttpClient client = new HttpClient(); using (HttpResponseMessage response = client.GetAsync(url).Result) { using (HttpContent content = response.Content) { var json = content.ReadAsStringAsync().Result; } }更新 1:
如果您想
Result用關鍵字替換對屬性的呼叫await,那麼這是可能的,但是您必須將此程式碼放在標記為async如下的方法中public async Task AsyncMethod() { string url = 'some url'; // best practice to create one HttpClient per Application and inject it HttpClient client = new HttpClient(); using (HttpResponseMessage response = await client.GetAsync(url)) { using (HttpContent content = response.Content) { var json = await content.ReadAsStringAsync(); } } }如果你錯過了
async方法中的關鍵字,你可能會得到一個編譯時錯誤,如下所示‘await’ 運算符只能在非同步方法中使用。考慮使用“async”修飾符標記此方法並將其返回類型更改為“Task<System.Threading.Tasks.Task>”。
更新 2:
回答有關將“WebClient”轉換為“WebRequest”的原始問題,這是您可以使用的程式碼,……但微軟(和我)建議您使用第一種方法(通過使用 HttpClient)。
string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; using (WebResponse response = httpWebRequest.GetResponse()) { HttpWebResponse httpResponse = response as HttpWebResponse; using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream())) { var json = reader.ReadToEnd(); } }如果您使用 C# 8 及更高版本,那麼您可以編寫非常優雅的程式碼
public async Task AsyncMethod() { string url = 'some url'; // best practice to create one HttpClient per Application and inject it HttpClient client = new HttpClient(); using HttpResponseMessage response = await client.GetAsync(url); using HttpContent content = response.Content; var json = await content.ReadAsStringAsync(); } // dispose will be called here, when you exit of the method, be aware of that更新 3
要知道為什麼
HttpClient更推薦WebRequest,WebClient您可以查閱以下連結。在 HttpClient 和 WebClient 之間做出決定
http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/
.NET 中的 WebClient 和 HTTPWebRequest 類有什麼區別?
http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx