Skip to content

Instantly share code, notes, and snippets.

@tocalai
Created January 18, 2022 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/59e1fe6ba5e0656ca46ec75216355f46 to your computer and use it in GitHub Desktop.
Save tocalai/59e1fe6ba5e0656ca46ec75216355f46 to your computer and use it in GitHub Desktop.
Http request help for retrieving result as string or as stream.
public class HttpRequestHelper
{
public static async Task<string> PostReturnString(RequestArgs query, string uri)
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(new Uri(uri),
new StringContent(JsonConvert.SerializeObject(query), Encoding.UTF8, "application/json"));
var responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
}
public static async Task<IReadOnlyCollection<Result>> PostReturnStream(RequestArgs query, , string uri)
{
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(uri));
request.Content = new StringContent(JsonConvert.SerializeObject(query), Encoding.UTF8, "application/json");
CancellationToken cancellationToken = new CancellationToken();
using (var httpClient = new HttpClient())
{
using (var result = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false))
{
using (var contentStream = await result.Content.ReadAsStreamAsync())
{
return await System.Text.Json.JsonSerializer.DeserializeAsync<List<Result>>(contentStream);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment