How to Replace WebClient with HttpClient?

偶尔善良 提交于 2019-11-27 06:21:00

问题


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?


回答1:


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/

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



来源:https://stackoverflow.com/questions/33020657/how-to-replace-webclient-with-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!