如何正确地将HttpClient与async/await一起使用? [英] How do I correctly use HttpClient with async/await?
本文介绍了如何正确地将HttpClient与async/await一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码出现两个错误:
I'm getting two errors for the following code:
public async Task<string> TestDownloadTask()
{
HttpResponseMessage response = null;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response.EnsureSuccessStatusCode();
response = await client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
}
return response.Content;
}
我得到了:
- 无法在等待"行上等待"System.Threading.Tasks.Task"
- 无法将表达式类型'System.Net.Http.Content'转换为返回类型'string'
我一直在尝试编写上面的代码,这些代码将从Web服务下载一个字符串,但是关于如何使用async和await和如何使用HttpClient似乎有很多相互矛盾的信息,我不知道我编写的代码有什么问题.
I've been attempting to write the above code that will download a string from a web service, but there seems to be a lot of conflicting information about how to use async and await and how to use HttpClient and I do not know what is wrong with the code I've written.
我要去哪里错了,应该怎么做呢?
Where am I going wrong and how should I be doing it instead?
推荐答案
此方法client.GetStringAsync
返回Task<string>
public Task<string> TestDownloadTask()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// You don't need await here
return client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
}
}
要使用上述功能:
public async void SomeMethod()
{
// await to get string content
string mystring = await TestDownloadTask();
}
这篇关于如何正确地将HttpClient与async/await一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文