42 lines
1.3 KiB
C#
Raw Normal View History

2024-12-16 21:23:13 +00:00
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpHelper
{
// Reuse a static HttpClient for the entire application to prevent socket exhaustion
private static readonly HttpClient client = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(10) // Set a timeout for the HTTP request
};
// Function to get the content of the URL
public static async Task<string> GetContentsAsync(string url)
{
try
{
// Send an HTTP GET request
HttpResponseMessage response = await client.GetAsync(url);
// Check if the request was successful (HTTP status code 200)
if (response.IsSuccessStatusCode)
{
// Read the response content as a string and return it
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
return content;
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
// Handle exceptions (e.g., network issues, invalid URLs)
Console.WriteLine($"Exception: {ex.Message}");
}
return null;
}
}