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.
c#: How to Post async request and get stream with httpclient?
Asked Answered
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.
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
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();
Note that this will read the entire stream into memory. Which is mostly not what users expect when they plan to use streaming. –
Technic
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()
© 2022 - 2024 — McMap. All rights reserved.