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

3

17

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.

Lanham answered 6/5, 2016 at 8:7 Comment(0)
T
30

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.

Technic answered 9/2, 2018 at 12:45 Comment(1)
If you need to add content to the POST request you can add it like that: var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(apiUrl), Content = content };Thwack
E
2

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();
Egomania answered 6/5, 2016 at 9:20 Comment(1)
Note that this will read the entire stream into memory. Which is mostly not what users expect when they plan to use streaming.Technic
O
-3

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()
Opera answered 6/5, 2016 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.