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 advice how I can change it from WebClient to be HttpClient?
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 calling to Result
property with the await
Keyword, then this is possible, but you have to put this code in a method which marked as async
as following
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
keyword from the method, you could get a Compile time error as the following
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
Update 2 :
Responding to your original question about converting the 'WebClient' to 'WebRequest' this is the code which you could use, ... But Microsoft ( and me ) recommended you to use the first approach (by using the 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 know why is HttpClient
is more recommended than WebRequest
and WebClient
you can consult the following links.
Need help deciding between HttpClient and WebClient
http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/
What difference is there between WebClient and HTTPWebRequest classes in .NET?
http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx