leonardzheng
leonardzheng

Reputation: 201

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.

Upvotes: 17

Views: 15868

Answers (3)

lanwin
lanwin

Reputation: 600

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.

Upvotes: 31

Cheng Chen
Cheng Chen

Reputation: 43523

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();

Upvotes: 2

Clovis Portron
Clovis Portron

Reputation: 582

Instead of HttpClient, maybe you should use HttpWebRequest ?

They offer both async method and the possibility to switch between post and get by setting their method property.

e.g:

var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
var postStream = await request.GetRequestStreamAsync()

Upvotes: -3

Related Questions