Getting content/message from HttpResponseMessage
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.
Related videos on Youtube
Clem
Updated on February 21, 2022Comments
-
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 about 11 yearsThanks, 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 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 about 11 yearsYes, but don't know how :) Sorry i'm beginner in c#
-
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 over 8 yearsNot sure why this isn't the accepted answer, especially since this gives you the ability to easily serialize contents into your objects.
-
stannius about 8 yearsReadAsStringAsync does not handle errors well IMHO.
-
Justin almost 8 yearsYou could also use Response.Content.ReadAsStringAsync().Result instead of using await
-
Maxime Rossini about 7 yearsThis answer is totally off-topic, the OP is using
HttpClient
, notHttpWebRequest
/HttpWebResponse
. -
Ginkgo about 7 yearsBeware 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 almost 7 yearsBy far the easiest to get up and running
-
Thomas.Benz over 6 yearsobject yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType)); should be var yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
-
Payam over 6 yearsThe question is in regard to HttpCient, your response is based on outdated and obsolete HttpWebRequest.
-
W.Leto over 5 yearsI used Request.Content.ReadAsAsync to parse Json and got horrible performance.
-
Almis over 4 yearsIs 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 over 4 yearsusing
.Result
any different?,httpContent.ReadAsStringAsync().Result
-
Maxime Rossini over 4 yearsPlease 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 almost 4 yearsDo NOT call
Result
on tasks. You risk locking up your application. Use async/await instead. -
benhorgen almost 4 yearsI 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 almost 4 years
.Result
would block the thread's execution on that line... where astxtBlock.Text.Wait()
blocks on the wait() call... so you're correct that basically there is no difference. But I suspecttxtBlock.Text.Wait()
would take a optional integer parameter so the GUI does not hang if the previousReadAsStringAsync()
call never returns. For example the following would block for no more than 1 secondtxtBlock.Text.Wait(1000)
-
Gerard Jaryczewski over 3 yearsGood or almost good. I needed to code like this: HttpResponseMessage response = ....; var responseBody = await response?.Content.ReadAsStringAsync();
-
benhorgen over 3 yearsIf 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 almost 3 yearsIt's generally bad practice to call
.Result
on a task, you'll block the main thread. -
John Sivertsen about 2 yearsResponse does not have a Result property. Correct would be
string result = await response.Content.ReadAsStringAsync()
-
Avrohom Yisroel almost 2 yearsThat'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.