如何用HttpClient替换WebClient?

joh*_* Gu 6 .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);
 }
Run Code Online (Sandbox Code Playgroud)

那么有人可以建议我如何将它从WebClient更改为HttpClient?

Hak*_*tık 20

您可以编写以下代码:

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;
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

更新1:

如果你想Resultawait关键字替换对属性的调用,那么这是可能的,但是你必须把这个代码放在一个标记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();
             }
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

如果您错过了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();
     }
}
Run Code Online (Sandbox Code Playgroud)

更新3

要了解为什么HttpClient比建议更多WebRequest,WebClient您可以参考以下链接.

需要帮助在HttpClient和WebClient之间做出决定

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

HttpClient与HttpWebRequest

.NET中的WebClient和HTTPWebRequest类之间有什么区别?

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

  • 将 `HttpClient` 包装在 `using` 块中是不好的。请不要这样做。有关原因的详细说明,请参阅下面的链接。长话短说,`HttpClient` 被设计为在整个应用程序中用作单个实例。它为您处理打开和关闭套接字。通过将它包装在一个 `using` 块中,它会在之后被处理,并且不会像预期的那样关闭套接字。一旦达到特定的每秒请求阈值,这可能会导致系统耗尽套接字。https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ (4认同)