This class is actually a wrapper around HttpWebRequest
to issue a POST
request with some payloads:
public class SendMessageService
{
public async Task Send()
{
var request = WebRequest.Create("url") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers["authorization"] = "token";
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ "\"app_id\": \"appId\","
+ "\"extra_parameter\": \"value\"}");
string responseContent = null;
try
{
using (var writer = await request.GetRequestStreamAsync())
{
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = await request.GetResponseAsync() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = await reader.ReadToEndAsync();
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
}
}
this class is going to be used in a web environment (ASP.NET Core app) so I registered this service as transient (created each time it is requested):
services.AddTransient<SendMessageService, SendMessageService>();
I would appreciate any improvement suggestions.