我第一次使用.net的Httpclient,发现很难。我已经成功调用服务器并从中接收到响应,但卡在了读取响应的阶段。以下是我的代码:
if (Method == HttpVerb.POST)
response = client.PostAsync(domain, new StringContent(parameters)).Result;
else
response = client.GetAsync(domain).Result;
if (response != null)
{
var responseValue = string.Empty;
Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
{
var stream = t.Result;
using (var reader = new StreamReader(stream))
{
responseValue = reader.ReadToEnd();
}
});
return responseValue;
}
虽然服务正在返回数据,但responseValue中仍然包含{}。我该如何解决这个问题?
该项目使用的是 .Net 4。
Task.Wait()
,请查看我的答案。 - DavidG