41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
|
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();
|
||
|
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;
|
||
|
}
|
||
|
}
|