如何用HttpClient替换WebClient? [英] How to Replace WebClient with HttpClient?

查看:165
本文介绍了如何用HttpClient替换WebClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net mvc Web应用程序中有以下WebClient:

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

那么有人能建议我如何将其从WebClient更改为HttpClient吗? / p>

So can anyone advice how I can change it from WebClient to be HttpClient?

推荐答案

您可以编写以下代码:

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 的方法中,如下所示

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

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

if you missed the async keyword from the method, you could get a Compile time error as the following


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

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'.

更新2

响应您有关将 WebClient转换为 WebRequest的原始问题,这是您可以使用的代码,但是Microsoft(和我)建议您使用第一种方法(通过使用HttpClient)。

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

更新3

要知道为什么 HttpClient WebRequest 更推荐,并且 WebClient 您可以查阅以下链接。

To know why is HttpClient is more recommended than WebRequest and WebClient you can consult the following links.

需要帮助在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替换WebClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆