Coder Perfect

Getting HttpResponseMessage’s content/message


I’m attempting to retrieve the contents of a HttpResponseMessage. It should be: “message”:”Action ” does not exist!”,”success”:false,”success”:false,”but I’m not sure how to get it out of HttpResponseMessage.

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://****?action=");
txtBlock.Text = Convert.ToString(response); //wrong!

txtBlock would be useful in this situation:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
  Vary: Accept-Encoding
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Wed, 10 Apr 2013 20:46:37 GMT
  Server: Apache/2.2.16
  Server: (Debian)
  X-Powered-By: PHP/5.3.3-7+squeeze14
  Content-Length: 55
  Content-Type: text/html

Asked by Clem

Solution #1

I believe the simplest solution is to simply replace the last line to

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

You won’t need to introduce any stream readers, and you won’t require any extension methods this way.

Answered by rudivonstaden

Solution #2

GetResponse must be called ().

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

Answered by Icemanind

Solution #3

Try this: Create an extension method that looks like this:

    public static string ContentToString(this HttpContent httpContent)
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;

then simply invoke the extension method as follows:

txtBlock.Text = response.Content.ContentToString();

I hope this information is useful to you.

Answered by MCurbelo

Solution #4

You can use the ReadAsAsync extension method to cast it to a specified type (for example, within tests):

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

or, for synchronous code, the following:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

Update: ReadAsAsync> has a generic option that returns a specified type instance instead of an object-declared one:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

Answered by taras-mytofir

Solution #5

rudivonstaden’s answer

txtBlock.Text = await response.Content.ReadAsStringAsync();

However, if you don’t want the method to be async, you can use

txtBlock.Text = response.Content.ReadAsStringAsync();

Wait() It’s crucial because we’re doing async operations and must wait for the task to finish before proceeding.

Answered by stanimirsp

Post is based on