2022-02-10 16:26:09 +00:00
|
|
|
namespace ASC.FederatedLogin.Helpers;
|
|
|
|
|
|
|
|
public static class RequestHelper
|
2019-06-06 13:34:46 +00:00
|
|
|
{
|
2022-02-10 16:26:09 +00:00
|
|
|
private readonly static HttpClient _httpClient = new HttpClient();
|
2022-01-13 11:19:39 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
public static string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary<string, string> headers = null, int timeout = 30000)
|
|
|
|
{
|
2022-03-09 17:15:51 +00:00
|
|
|
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(uri);
|
2019-06-06 13:34:46 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
var request = new HttpRequestMessage();
|
|
|
|
request.RequestUri = new Uri(uri);
|
|
|
|
request.Method = new HttpMethod(method);
|
2021-10-12 10:14:33 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
_httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
|
2021-10-12 10:14:33 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
if (headers != null)
|
|
|
|
{
|
|
|
|
foreach (var key in headers.Keys)
|
2019-06-06 13:34:46 +00:00
|
|
|
{
|
2022-02-10 16:26:09 +00:00
|
|
|
request.Headers.Add(key, headers[key]);
|
2019-06-06 13:34:46 +00:00
|
|
|
}
|
2022-02-10 16:26:09 +00:00
|
|
|
}
|
2019-06-06 13:34:46 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
var bytes = Encoding.UTF8.GetBytes(body ?? "");
|
|
|
|
if (request.Method != HttpMethod.Get && bytes.Length > 0)
|
|
|
|
{
|
|
|
|
request.Content = new ByteArrayContent(bytes, 0, bytes.Length);
|
|
|
|
if (!string.IsNullOrEmpty(contentType))
|
2019-06-06 13:34:46 +00:00
|
|
|
{
|
2022-02-10 16:26:09 +00:00
|
|
|
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
2019-06-06 13:34:46 +00:00
|
|
|
}
|
2022-02-10 16:26:09 +00:00
|
|
|
}
|
2019-06-06 13:34:46 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
using var response = _httpClient.Send(request);
|
|
|
|
using var stream = response.Content.ReadAsStream();
|
|
|
|
if (stream == null)
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
2022-02-10 16:06:48 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
using var readStream = new StreamReader(stream);
|
2021-11-24 19:34:39 +00:00
|
|
|
|
2022-02-10 16:26:09 +00:00
|
|
|
return readStream.ReadToEnd();
|
2019-06-06 13:34:46 +00:00
|
|
|
}
|
2022-02-10 16:26:09 +00:00
|
|
|
}
|