C#从HttpResponseMessage读取

时间:2014-07-16 11:33:38

标签: c# .net httpclient

我第一次使用.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。

2 个答案:

答案 0 :(得分:8)

您正在创建异步任务,但在返回之前不等待它完成。这意味着您的responseValue永远不会被设置。

要解决此问题,请在返回之前执行此操作:

task.Wait();

所以你的功能现在看起来像这样:

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

     task.Wait();

     return responseValue;
}

如果您更喜欢使用await(您可能应该使用),那么您需要使此代码包含在async中。所以这个:

public string GetStuffFromSomewhere()
{
    //Code above goes here

    task.Wait();
}

变为:

public async string GetStuffFromSomewhere()
{
    //Code above goes here

    await ...
}

答案 1 :(得分:0)

试试这个

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(obj.Url);
                    HttpWebResponse response = null;

                    try
                    {
                        response = request.GetResponse() as HttpWebResponse;
                    }
                    catch (Exception ex)
                    {
                    }