common/SoftwareAccessHelper/LocalWebRequest.cs
2026-04-23 17:50:07 +02:00

651 lines
22 KiB
C#

using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Xylem.Common.Logic.SoftwareAccessHelper
{
/// <summary>
/// Web request
/// </summary>
public static class LocalWebRequest
{
/// <summary>
/// Web request with asynchronous operation and response code or exception response, json object input and/or dictionary
/// </summary>
/// <param name="url"></param>
/// <param name="responseCode"></param>
/// <param name="ex"></param>
/// <param name="timeoutMs"></param>
/// <param name="json"></param>
/// <param name="header"></param>
/// <returns></returns>
public static Boolean PostRequestAsync(String url, ref Int32 responseCode, ref Exception ex, Int32? timeoutMs = null, Object json = null, Dictionary<String, String> header = null)
{
try
{
var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header);
responseCode = r.StatusCode.GetHashCode();
if (r.StatusCode == HttpStatusCode.OK)
{
return true;
}
if (r.StatusCode == HttpStatusCode.InternalServerError)
{
ex = new Exception(r.Content);
}
}
catch (Exception error)
{
ex = error;
}
return false;
}
/// <summary>
/// Web request with asynchronous operation and true/false return, json object input and/or dictionary
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="json"></param>
/// <param name="header"></param>
/// <returns></returns>
public static Boolean PostRequestAsync(String url, Int32? timeoutMs = null, Object json = null, Dictionary<String, String> header = null)
{
try
{
var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header);
if (r.StatusCode == HttpStatusCode.OK)
{
return true;
}
}
catch (Exception)
{
// Log
}
return false;
}
/// <summary>
/// Web request with asynchronous operation with string return, json object input and/or dictionary
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="json"></param>
/// <param name="header"></param>
/// <returns></returns>
public static String PostRequestAsyncAndGetContent(String url, Int32? timeoutMs = null, Object json = null, Dictionary<String, String> header = null)
{
try
{
var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header);
if (r.StatusCode == HttpStatusCode.OK)
{
return r.Content;
}
}
catch (Exception)
{
// Log
}
return string.Empty;
}
/// <summary>
/// Web request with asynchronous operation, binary file byte array input, response string output
/// </summary>
/// <param name="url"></param>
/// <param name="fileName"></param>
/// <param name="content"></param>
/// <param name="response"></param>
/// <param name="timeoutMs"></param>
/// <returns></returns>
public static Boolean PostBinaryFileRequestAsync(String url, String fileName, Byte[] content, out String response, Int32? timeoutMs = null)
{
try
{
var client = new RestClient(url);
//WebRequest.DefaultWebProxy = null;
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = false;
request.AddHeader("Content-Type", "multipart/form-data");
request.Files.Add(new FileParameter
{
Name = "file",
Writer = (s) =>
{
var stream = new MemoryStream(content);
stream.CopyTo(s);
stream.Dispose();
},
FileName = fileName,
ContentType = "multipart/form-data",
ContentLength = content.Length
});
var r = client.ExecuteAsPost(request, Method.POST.ToString());
response = r.Content;
return r.StatusCode == HttpStatusCode.OK;
}
catch (Exception)
{
response = string.Empty;
return false;
}
}
/// <summary>
/// Web request with asynchronous operation, binary file input
/// </summary>
/// <param name="url"></param>
/// <param name="fileName"></param>
/// <param name="content"></param>
/// <param name="timeoutMs"></param>
/// <returns></returns>
public static Boolean PostBinaryFileRequestAsync(String url, String fileName, Byte[] content, Int32? timeoutMs = null)
{
try
{
var client = new RestClient(url);
// WebRequest.DefaultWebProxy = null;
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = false;
request.AddHeader("Content-Type", "multipart/form-data");
request.Files.Add(new FileParameter
{
Name = "file",
Writer = (s) =>
{
var stream = new MemoryStream(content);
stream.CopyTo(s);
stream.Dispose();
},
FileName = fileName,
ContentType = "multipart/form-data",
ContentLength = content.Length
});
var r = client.ExecuteAsPost(request, Method.POST.ToString());
return r.StatusCode == HttpStatusCode.OK;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Web request with asynchronous operation
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="files"></param>
/// <param name="header"></param>
/// <returns></returns>
public static IRestResponse PostBinaryRequestAndGetResponseAsync(String url, Int32? timeoutMs = null,
Dictionary<String, String> files = null, Dictionary<String, String> header = null)
{
try
{
var client = new RestClient(url);
//WebRequest.DefaultWebProxy = null;
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = false;
if (header != null)
{
foreach (var item in header)
{
if (item.Key != "Content-Type" && item.Key != "Accept")
{
request.AddHeader(item.Key, item.Value);
}
}
}
request.AddHeader("Content-Type", "multipart/form-data");
if (files != null)
{
foreach (var item in files)
{
request.AddFile(item.Key, item.Value);
}
}
var r = client.ExecuteAsPost(request, Method.POST.ToString());
return r;
}
catch (Exception error)
{
return new RestResponse
{
StatusCode = HttpStatusCode.InternalServerError,
Content = error.ToString()
};
}
}
/// <summary>
/// Post Request Async
/// </summary>
/// <remarks date="2024-Sep-09" author="Stoyan Slatev">
/// - Initial.
/// </remarks>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="json"></param>
/// <param name="httpStatus"></param>
/// <returns></returns>
public static String PostRequestAsync(String url, Double timeoutMs, out HttpStatusCode httpStatus, Object json = null)
{
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
var postedJson = JsonConvert.SerializeObject(json, Formatting.Indented);
var postedBody = new StringContent(postedJson);
postedBody.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
var posted = httpClient
.PostAsync(url, postedBody)
.Result;
httpStatus = posted.StatusCode;
return posted.Content.ReadAsStringAsync().Result;
}
catch (Exception error)
{
httpStatus = HttpStatusCode.ServiceUnavailable;
return error.Message;
}
}
/// <summary>
/// Web request
/// </summary>
/// <param name="url"></param>
/// <param name="httpStatus"></param>
/// <param name="timeoutMs"></param>
/// <returns></returns>
public static String GetRequest(String url, Double timeoutMs, out HttpStatusCode httpStatus)
{
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
var response = httpClient
.GetAsync(url)
.Result;
httpStatus = response.StatusCode;
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception error)
{
httpStatus = HttpStatusCode.ServiceUnavailable;
return error.Message;
}
}
/// <summary>
/// Web request with asynchronous operation
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="json"></param>
/// <param name="header"></param>
/// <returns></returns>
public static IRestResponse PostRequestAndGetResponseAsync(String url, Int32? timeoutMs = null, Object json = null,
Dictionary<String, String> header = null)
{
try
{
var client = new RestClient(url);
client.AddDefaultHeader("Accept", "application/json");
//WebRequest.DefaultWebProxy = null;
ServicePointManager.Expect100Continue = false;
var request = new RestRequest(Method.POST);
if (header != null)
{
foreach (var item in header)
{
if (item.Key != "Content-Type" && item.Key != "Accept")
{
request.AddHeader(item.Key, item.Value);
}
}
}
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
if (json != null)
{
request.AddJsonBody(json);
}
var r = client.ExecuteAsPost(request, Method.POST.ToString());
return r;
}
catch (Exception error)
{
return new RestResponse
{
StatusCode = HttpStatusCode.InternalServerError,
Content = error.ToString()
};
}
}
#region HTTP String extensions
public static HttpResponse<T> DeleteAsJson<T>(this String url, Object json = null, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.DELETE.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> GetAsJson<T>(this String url, Object json = null, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.GET.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> PostAsJson<T>(this String url, Object json = null, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.POST.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> PutAsJson<T>(this String url, Object json = null, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.PUT.AsJson<T>(url, headersHandler, json, timeoutMs);
}
#endregion HTTP String extensions
#region HTTP Object extensions
public static HttpResponse<T> DeleteAsJson<T>(this Object json, String url, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.DELETE.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> GetAsJson<T>(this Object json, String url, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.GET.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> GetAsJson<T>(String url, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.GET.AsJson<T>(url, headersHandler, null, timeoutMs);
}
public static HttpResponse<T> PostAsJson<T>(this Object json, String url, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.POST.AsJson<T>(url, headersHandler, json, timeoutMs);
}
public static HttpResponse<T> PutAsJson<T>(this Object json, String url, Action<RestRequestHeaders> headersHandler = null, Int32? timeoutMs = null)
{
return Method.PUT.AsJson<T>(url, headersHandler, json, timeoutMs);
}
#endregion HTTP Object extensions
/// <summary>
/// Web request
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="header"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
public static String DeleteRequest(String url, Int32? timeoutMs = null, Dictionary<String, String> header = null, Boolean isRetry = false)
{
var ret = DeleteRequestWithError(url, out var temp, timeoutMs, header, isRetry);
if (temp != 200)
{
throw new ApplicationException($"WebRequest Status {temp}");
}
return ret;
}
/// <summary>
/// Web request with asynchronous operation, error code response
/// </summary>
/// <param name="url"></param>
/// <param name="errorCode"></param>
/// <param name="timeoutMs"></param>
/// <param name="header"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
public static String DeleteRequestWithError(String url, out Int32 errorCode, Int32? timeoutMs = null, Dictionary<String, String> header = null, Boolean isRetry = false)
{
var client = new RestClient(url);
var request = new RestRequest(Method.DELETE);
ServicePointManager.Expect100Continue = false;
if (!timeoutMs.HasValue)
{
timeoutMs = 800;
}
request.Timeout = timeoutMs.Value;
if (header != null)
{
foreach (var item in header)
{
if (item.Key != "Accept")
{
request.AddHeader(item.Key, item.Value);
}
}
}
request.AddHeader("Accept", "application/json");
var r = client.Execute(request);
errorCode = r.StatusCode.GetHashCode();
if (r.StatusCode == HttpStatusCode.OK)
{
return r.Content;
}
if (r.StatusCode != 0)
return r.Content;
return !isRetry ? DeleteRequest(url, timeoutMs, header, true) : r.Content;
}
/// <summary>
/// Web request
/// </summary>
/// <param name="url"></param>
/// <param name="timeoutMs"></param>
/// <param name="header"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
public static String GetRequest(String url, Int32? timeoutMs = null, Dictionary<String, String> header = null, Boolean isRetry = false)
{
//if (true && (url.Contains("sla12iis01/MeterProcessState") || url.Contains("sla12iis01.emea.sensus.net/MeterProcessState")))
//{
// url = url.Replace("sla12iis01/MeterProcessState", "delaz1web01/MeterProcessState").Replace("sla12iis01.emea.sensus.net/MeterProcessState", "delaz1web01/MeterProcessState")
//}
var ret = GetRequestWithError(url, out var temp, timeoutMs, header, isRetry);
if (temp != 200)
{
throw new ApplicationException($"WebRequest Status {temp}");
}
return ret;
}
/// <summary>
/// Web request with asynchronous operation, error code response
/// </summary>
/// <param name="url"></param>
/// <param name="errorCode"></param>
/// <param name="timeoutMs"></param>
/// <param name="header"></param>
/// <param name="isRetry"></param>
/// <returns></returns>
public static String GetRequestWithError(String url, out Int32 errorCode, Int32? timeoutMs = null, Dictionary<String, String> header = null, Boolean isRetry = false)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
ServicePointManager.Expect100Continue = false;
if (!timeoutMs.HasValue)
{
timeoutMs = 800;
}
request.Timeout = timeoutMs.Value;
if (header != null)
{
foreach (var item in header)
{
if (item.Key != "Accept")
{
request.AddHeader(item.Key, item.Value);
}
}
}
request.AddHeader("Accept", "application/json");
var r = client.Get(request);
errorCode = r.StatusCode.GetHashCode();
if (r.StatusCode == HttpStatusCode.OK)
{
return r.Content;
}
if (r.StatusCode != 0)
return r.Content;
return !isRetry ? GetRequest(url, timeoutMs, header, true) : r.Content;
}
private static HttpResponse<T> AsJson<T>(this Method method, String url, Action<RestRequestHeaders> headersHandler = null, Object model = null, Int32? timeoutMs = null)
{
var httpResponse = new HttpResponse<T>();
try
{
var client = new RestClient(url);
var request = new RestRequest(method);
var headers = new RestRequestHeaders(request)
{
ContentType = "application/json",
Accept = "application/json"
};
headersHandler?.Invoke(headers);
if (model != null)
{
if (method == Method.GET)
{
request.AddObject(model);
}
else
{
request.AddJsonBody(model);
}
}
ServicePointManager.Expect100Continue = false;
var response = client.Execute(request);
httpResponse.HttpStatusCode = response.StatusCode;
if (HttpStatusCode.OK <= response.StatusCode && response.StatusCode < HttpStatusCode.BadRequest)
{
if (!string.IsNullOrWhiteSpace(response.Content))
{
httpResponse.Value = JsonConvert.DeserializeObject<T>(response.Content);
}
else
{
httpResponse.Errors = new Dictionary<String, String>()
{
{ nameof(response.Content), $"{response.Content}" },
};
}
}
else
{
httpResponse.Errors = JsonConvert.DeserializeObject<Dictionary<String, String>>(response.Content);
if (httpResponse.Errors is null)
{
httpResponse.Errors = new Dictionary<String, String>()
{
{ nameof(response.ErrorException), $"{response.ErrorException}" },
{ nameof(response.ErrorMessage), $"{response.ErrorMessage}" },
{ nameof(response.Content), $"{response.Content}" },
};
}
}
}
catch (Exception error)
{
httpResponse.HttpStatusCode = HttpStatusCode.InternalServerError;
httpResponse.Errors = new Dictionary<String, String>()
{
{ nameof(Exception), $"{error}" }
};
}
return httpResponse;
}
}
}