You can write the following code:
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;
}
}
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 = '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();
}
}
}
if you missed the async keyword from the method, you could get a Compile-time error like 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<System.Threading.Tasks.Task>'.
Update 2 :
Responding to your original question about converting the 'WebClient' to 'WebRequest' this is the code that 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();
}
}
if you use C# 8 and above, then you can write very elegant code
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
Update 3
To know why is HttpClient is more recommended than WebRequest and WebClient you can consult the following links.
Deciding between HttpClient and WebClient
http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/
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