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:
如果你想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();
}
}
}
}
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/
.NET中的WebClient和HTTPWebRequest类之间有什么区别?
http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx
| 归档时间: |
|
| 查看次数: |
8447 次 |
| 最近记录: |