Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: How to Post async request and get stream with httpclient?

I need to send async request to the server and get the information from the response stream. I'm using HttpClient.GetStreamAsync(), but the server response that POST should be used. Is there a similar method like PostStreamAsync()? Thank you.

like image 551
leonardzheng Avatar asked May 06 '16 08:05

leonardzheng


Video Answer


2 Answers

If you want to use HttpClient for streaming large data then you should not use PostAsync cause message.Content.ReadAsStreamAsync would read the entire stream into memory. Instead you can use the following code block.

var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3100/api/test");
var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();

The key thing here is the HttpCompletionOption.ResponseHeadersRead option which tells the client not to read the entire content into memory.

like image 90
lanwin Avatar answered Oct 22 '22 04:10

lanwin


Use HttpClient.PostAsync and you can get the response stream via HttpResponseMessage.Content.ReadAsStreamAsync() method.

var message = await client.PostAsync(url, content);
var stream = await message.Content.ReadAsStreamAsync();
like image 2
Cheng Chen Avatar answered Oct 22 '22 04:10

Cheng Chen