如何用HttpClient替换WebClient?

时间:2015-10-08 15:58:40

标签: .net webclient webrequest webclient-download

我的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吗?

1 个答案:

答案 0 :(得分:15)

您可以编写以下代码:

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

更新1

如果您想将Result属性的调用替换为await关键字,那么这是可行的,但您必须将此代码放在标记为async的方法中以下

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

如果您错过了方法中的async关键字,则可能会出现编译时错误,如下所示

  

'await'运算符只能在异步方法中使用。考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'。

更新2

回答关于将“WebClient”转换为“WebRequest”的原始问题,这是您可以使用的代码,...但Microsoft(和我)建议您使用第一种方法(使用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();
     }
}

更新3

要了解为什么HttpClient比[{1}}和WebRequest更推荐,您可以参考以下链接。

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