42 lines
1.4 KiB
C#
42 lines
1.4 KiB
C#
|
// The URL of the API or website you want to make a request to
|
||
|
using System;
|
||
|
using System.Net.Http;
|
||
|
using System.Text;
|
||
|
using System.Threading.Tasks;
|
||
|
|
||
|
static class HTTP {
|
||
|
public static async Task<string> get(string url){
|
||
|
// Create an instance of HttpClient
|
||
|
using (HttpClient client = new HttpClient())
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
// Send a GET request to the specified URL
|
||
|
HttpResponseMessage response = await client.GetAsync(url);
|
||
|
|
||
|
// Check if the response is successful (status code 200)
|
||
|
if (response.IsSuccessStatusCode)
|
||
|
{
|
||
|
// Read the response content as a string
|
||
|
string responseData = await response.Content.ReadAsStringAsync();
|
||
|
|
||
|
// Print the response to the console
|
||
|
Console.WriteLine(responseData);
|
||
|
return responseData;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
// Handle the error if the status code is not successful
|
||
|
Console.WriteLine("Error: " + response.StatusCode);
|
||
|
}
|
||
|
}
|
||
|
catch (Exception ex)
|
||
|
{
|
||
|
// Handle any exceptions (e.g., network errors)
|
||
|
Console.WriteLine("Exception occurred: " + ex.Message);
|
||
|
}
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
}
|