Getting content/message from HttpResponseMessage

306,994

Solution 1

You need to call GetResponse().

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

Solution 2

I think the easiest approach is just to change the last line to

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

This way you don't need to introduce any stream readers and you don't need any extension methods.

Solution 3

Try this, you can create an extension method like this:

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

and then, simple call the extension method:

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

I hope this help you ;-)

Solution 4

If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:

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

or following for synchronous code:

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

Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:

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

Solution 5

By the answer of rudivonstaden

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

but if you don't want to make the method async you can use

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

Wait() it's important, becаuse we are doing async operations and we must wait for the task to complete before going ahead.

Share:
306,994

Related videos on Youtube

Clem
Author by

Clem

Updated on February 21, 2022

Comments

  • Clem
    Clem about 2 years

    I'm trying to get content of HttpResponseMessage. It should be: {"message":"Action '' does not exist!","success":false}, but I don't know, how to get it out of HttpResponseMessage.

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

    In this case txtBlock would have value:

    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
    }
    
  • Clem
    Clem about 11 years
    Thanks, but why i get this error here: "System.Net.Http.HttpResponseMessage' does not contain a definition for 'GetResponseStream' and no extension method 'GetResponseStream' accepting a first argument of type 'System.Net.Http.HttpResponseMessage' could be found"
  • Icemanind
    Icemanind about 11 years
    @Klemzy - Because you are calling it Asynchronisly. Try using Content property instead. Look at the example here. Scroll down to the second step.
  • Clem
    Clem about 11 years
    Yes, but don't know how :) Sorry i'm beginner in c#
  • Icemanind
    Icemanind about 11 years
    @Klemzy - Look at the example here. Scroll down to the second step. If you can't figure it out, I'll edit my answer and give you an example for you
  • Jason McKindly
    Jason McKindly over 8 years
    Not sure why this isn't the accepted answer, especially since this gives you the ability to easily serialize contents into your objects.
  • stannius
    stannius about 8 years
    ReadAsStringAsync does not handle errors well IMHO.
  • Justin
    Justin almost 8 years
    You could also use Response.Content.ReadAsStringAsync().Result instead of using await
  • Maxime Rossini
    Maxime Rossini about 7 years
    This answer is totally off-topic, the OP is using HttpClient, not HttpWebRequest / HttpWebResponse.
  • Ginkgo
    Ginkgo about 7 years
    Beware though: ReadAsStringAsync() can throw if you have emoticons or some other Unicode characters in the response. I had to use Streams (like in the accepted answer) to overcome that.
  • Aage
    Aage almost 7 years
    By far the easiest to get up and running
  • Thomas.Benz
    Thomas.Benz over 6 years
    object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType)); should be var yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
  • Payam
    Payam over 6 years
    The question is in regard to HttpCient, your response is based on outdated and obsolete HttpWebRequest.
  • W.Leto
    W.Leto over 5 years
    I used Request.Content.ReadAsAsync to parse Json and got horrible performance.
  • Almis
    Almis over 4 years
    Is it purposefully not disposed of Streams? I know this might sound like a silly question for those who are used to dispose of everything that implements IDisposable but there are exceptions like for example HttpClient.
  • mkb
    mkb over 4 years
    using .Result any different?, httpContent.ReadAsStringAsync().Result
  • Maxime Rossini
    Maxime Rossini over 4 years
    Please use await instead of .Result... or use a synchronous HTTP client instead, if your code can't handle async programming. But any modern code should, otherwise it may be a sign your application is doing something wrong.
  • eltiare
    eltiare almost 4 years
    Do NOT call Result on tasks. You risk locking up your application. Use async/await instead.
  • benhorgen
    benhorgen almost 4 years
    I would not say never... sometimes quick and dirty gets it done. But I agree you do run the risk of ReadAsStringAsync() not returning, so make sure not to call it on your GUI or main application thread.
  • benhorgen
    benhorgen almost 4 years
    .Result would block the thread's execution on that line... where as txtBlock.Text.Wait() blocks on the wait() call... so you're correct that basically there is no difference. But I suspect txtBlock.Text.Wait() would take a optional integer parameter so the GUI does not hang if the previous ReadAsStringAsync() call never returns. For example the following would block for no more than 1 second txtBlock.Text.Wait(1000)
  • Gerard Jaryczewski
    Gerard Jaryczewski over 3 years
    Good or almost good. I needed to code like this: HttpResponseMessage response = ....; var responseBody = await response?.Content.ReadAsStringAsync();
  • benhorgen
    benhorgen over 3 years
    If I understand your question correctly, I would answer "almost good". Depending on your code execution pattern (e.g. single thread or multi-threaded) should determine your approach. In regards to this answer which you're commenting on (assuming single threaded execution is ok) then I would call var responseBody = response.Content.ReadAsStringAsync().Result;
  • db2
    db2 almost 3 years
    It's generally bad practice to call .Result on a task, you'll block the main thread.
  • John Sivertsen
    John Sivertsen about 2 years
    Response does not have a Result property. Correct would be string result = await response.Content.ReadAsStringAsync()
  • Avrohom Yisroel
    Avrohom Yisroel almost 2 years
    That's soooo counter-intuitive! Why didn't they make it more obvious? Agree that this should be the accepted answer. Glad it's got the most votes.