简体   繁体   中英

C# read from HttpResponseMessage

I am using .net's Httpclient for the first time and finding it very hard. 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. How should I fix the issue?

The project is in .Net 4.

You are creating an asynchronous task but not waiting for it to complete before returning. This means your responseValue never gets set.

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 . 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)
                    {
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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