Getting content/message from HttpResponseMessage

C#Windows 8Windows Store-Apps

C# Problem Overview


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
}

C# Solutions


Solution 1 - C#

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 2 - C#

You need to call GetResponse().

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

Solution 3 - C#

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 - C#

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 - C#

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.

Solution 6 - C#

The quick answer I suggest is:

response.Result.Content.ReadAsStringAsync().Result

Solution 7 - C#

I think the following image helps for those needing to come by T as the return type.

enter image description here

Solution 8 - C#

You can use the GetStringAsync method:

var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);

Solution 9 - C#

Using block:

using System;
using System.Net;
using System.Net.Http;

This Function will create new HttpClient object, set http-method to GET, set request URL to the function "Url" string argument and apply these parameters to HttpRequestMessage object (which defines settings of SendAsync method). Last line: function sends async GET http request to the specified url, waits for response-message's .Result property(just full response object: headers + body/content), gets .Content property of that full response(body of request, without http headers), applies ReadAsStringAsync() method to that content(which is also object of some special type) and, finally, wait for this async task to complete using .Result property once again in order to get final result string and then return this string as our function return.

static string GetHttpContentAsString(string Url)
    {   
        HttpClient HttpClient = new HttpClient();
        HttpRequestMessage RequestMessage = new HttpRequestMessage(HttpMethod.Get, Url);
        return HttpClient.SendAsync(RequestMessage).Result.Content.ReadAsStringAsync().Result;
    }

Shorter version, which does not show the full "transformational" path of our http-request and uses GetStringAsync method of HttpClient object. Function just creates new instance of HttpClient class (an HttpClient object), uses GetStringAsync method to get response body(content) of our http request as an async-task result\promise, and then uses .Result property of that async-task-result to get final string and after that simply returns this string as a function return.

static string GetStringSync(string Url)
    {
        HttpClient HttpClient = new HttpClient();
        return HttpClient.GetStringAsync(Url).Result;
    }

Usage:

const string url1 = "https://microsoft.com";
const string url2 = "https://stackoverflow.com";

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; /*sets TLC protocol version explicitly to modern version, otherwise C# could not make http requests to some httpS sites, such as https://microsoft.com*/

Console.WriteLine(GetHttpContentAsString(url1)); /*gets microsoft main page html*/
Console.ReadLine(); /*makes some pause before second request. press enter to make second request*/
Console.WriteLine(GetStringSync(url2)); /*gets stackoverflow main page html*/
Console.ReadLine(); /*press enter to finish*/

Full code:

enter image description here

Solution 10 - C#

Updated answer as of 2022-02:

var stream = httpResponseMessage.Content.ReadAsStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
var responseBodyBytes = ms.ToArray();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClemView Question on Stackoverflow
Solution 1 - C#rudivonstadenView Answer on Stackoverflow
Solution 2 - C#IcemanindView Answer on Stackoverflow
Solution 3 - C#MCurbeloView Answer on Stackoverflow
Solution 4 - C#taras-mytofirView Answer on Stackoverflow
Solution 5 - C#stanimirspView Answer on Stackoverflow
Solution 6 - C#benhorgenView Answer on Stackoverflow
Solution 7 - C#snrView Answer on Stackoverflow
Solution 8 - C#HinrichView Answer on Stackoverflow
Solution 9 - C#vritmeView Answer on Stackoverflow
Solution 10 - C#ConwayView Answer on Stackoverflow