C# / .NET इंटीग्रेशन
अपने .NET एप्लिकेशन में SMSBAT API को इंटीग्रेट करना अंतर्निहित HttpClient क्लास से आसान है।
HttpClient का उपयोग (.NET Core / .NET 5+)
यहाँ HttpClient और सीरियलाइज़ेशन के लिए System.Text.Json का उपयोग करके संदेश को एसिंक्रोनस रूप से भेजने का उदाहरण है।
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace SmsbatIntegration
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
string url = "https://api.smsbat.com/bat/messagelist";
string apiKey = "YOUR_API_KEY_HERE";
// Create the payload using anonymous objects
var payload = new
{
messages = new[]
{
new
{
from = "ALPHANAME",
to = "380501234567",
text = "Hello from C# and .NET!",
type = "sms"
}
}
};
// Serialize the payload to JSON
string jsonPayload = JsonSerializer.Serialize(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// Set the Authorization Header
client.DefaultRequestHeaders.Add("X-Authorization-Key", apiKey);
try
{
// Send the POST request
HttpResponseMessage response = await client.PostAsync(url, content);
// Read the response content
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status Code: {(int)response.StatusCode}");
Console.WriteLine($"Response: {responseBody}");
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
}
}
}
}
RestSharp का उपयोग
अगर आपका प्रोजेक्ट पहले से RestSharp का उपयोग करता है, तो आप अनुरोध की संरचना को सरल बनाने के लिए उसका उपयोग कर सकते हैं।
NuGet पैकेज इंस्टॉल करें:
dotnet add package RestSharp
using System;
using System.Threading.Tasks;
using RestSharp;
namespace SmsbatIntegrationRestSharp
{
class Program
{
static async Task Main(string[] args)
{
var options = new RestClientOptions("https://api.smsbat.com");
var client = new RestClient(options);
var request = new RestRequest("/bat/messagelist", Method.Post);
request.AddHeader("X-Authorization-Key", "YOUR_API_KEY_HERE");
var payload = new
{
messages = new[]
{
new
{
from = "ALPHANAME",
to = "380501234567",
text = "Hello from RestSharp!",
type = "sms"
}
}
};
// Automatically serializes object to JSON and sets Content-Type
request.AddJsonBody(payload);
try
{
var response = await client.ExecuteAsync(request);
Console.WriteLine($"Status Code: {(int)response.StatusCode}");
Console.WriteLine($"Response: {response.Content}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}