简体   繁体   English

C#从HttpResponseMessage读取

[英]C# read from HttpResponseMessage

I am using .net's Httpclient for the first time and finding it very hard. 我第一次使用.net的Httpclient并且很难找到它。 I have managed to call the server and receive response from it but stuck at reading from the response. 我已设法调用服务器并接收来自它的响应,但仍坚持从响应中读取。 Here is my code: 这是我的代码:

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 has {} in it although the service is returning data. 虽然服务正在返回数据,但responseValue中有{}。 How should I fix the issue? 我该如何解决这个问题?

The project is in .Net 4. 该项目位于.Net 4。

You are creating an asynchronous task but not waiting for it to complete before returning. 您正在创建异步任务,但在返回之前不等待它完成。 This means your responseValue never gets set. 这意味着您的responseValue永远不会被设置。

To fix this, before your return do this: 要解决此问题,请在返回之前执行此操作:

task.Wait();

So your function now looks like this: 所以你的功能现在看起来像这样:

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

If you prefer to use await (which you possibly should), then you need to make the function this code is contained in async . 如果您更喜欢使用await (您可能应该使用),那么您需要使该代码包含在async So this: 所以这:

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

    task.Wait();
}

Becomes: 变为:

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

    await ...
}

Try this 尝试这个

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM