可以编写如下代码:
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
更新 1:
如果您想用await 关键字替换对Result 属性的调用,那么这是可能的,但是您必须将此代码放入标记为async 的方法中,如下所示
public async Task AsyncMethod()
{
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
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”的原始问题,这是您可以使用的代码,......但微软(和我)建议您使用第一种方法(通过使用 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();
}
}
如果你使用 C# 8 及以上版本,那么你可以编写非常优雅的代码
public async Task AsyncMethod()
{
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
var json = await content.ReadAsStringAsync();
} // dispose will be called here, when you exit of the method, be aware of that
更新 3
要知道为什么HttpClient 比WebRequest 和WebClient 更推荐,您可以参考以下链接。
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