How to replace WebClient with HttpClient?

I have the following WebClient inside my asp.net mvc web application:

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); } 

So can anyone advise how I can change it from WebClient to be HttpClient?

+2
webclient webrequest webclient-download
08 Oct '15 at 15:58
source share
1 answer

You can write the following code:

 string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = client.GetAsync(url).Result) { using (HttpContent content = response.Content) { var json = content.ReadAsStringAsync().Result; } } } 

Update 1 :

if you want to replace the call property with Result with the await keyword, this is possible, but you should put this code in a method that is marked as async as follows

 public async Task AsyncMethod() { string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(url)) { using (HttpContent content = response.Content) { var json = await content.ReadAsStringAsync(); } } } } 

if you missed the async from the method, you may get a compile-time error as follows

The wait statement can only be used in the asynchronous method. Consider labeling this method with the async modifier and change its return type to Task.

Update 2 :

Answering your initial question about converting "WebClient" to "WebRequest", this is code that you could use ... But Microsoft (and I) recommended that you use the first approach (using 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(); } } 

Update 3

To find out why HttpClient more recommended than WebRequest and WebClient , you can refer to the following links.

Need help deciding between HttpClient and WebClient

http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/

HttpClient vs HttpWebRequest

What is the difference between the WebClient and HTTPWebRequest classes in .NET?

http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx

+6
Oct 09 '15 at 6:55
source



All Articles