We're developing a application in Visual C# 2022. Our goal is to allow users to input a URL, retrieve the data from that URL, and generate HTML content for them. However, we're encountering a runtime error when users input invalid URLs, as our application attempts to fetch data from non-existent web pages.
We've been investigating methods to determine whether the provided URL is accessible or not. By "accessible," we mean whether the URL can be reached and data can be retrieved from it, rather than simply checking domain availability.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class UrlChecker
{
public async Task<bool> CheckUrl(string url)
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
return response.StatusCode == HttpStatusCode.OK;
}
catch (HttpRequestException)
{
// URL is not valid or doesn't exist
return false;
}
}
}
}
class Program
{
static async Task Main(string[] args)
{
string urlToCheck = "https://quickpickdeal.com/api/employee";
UrlChecker urlChecker = new UrlChecker();
bool isValid = await urlChecker.CheckUrl(urlToCheck);
if (isValid)
{
Console.WriteLine("URL is valid and exists.");
}
else
{
Console.WriteLine("URL is not valid or doesn't exist.");
}
}
}
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class UrlChecker
{
public async Task<bool> CheckUrl(string url)
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
return response.StatusCode == HttpStatusCode.OK;
}
catch (HttpRequestException)
{
// URL is not valid or doesn't exist
return false;
}
}
}
}
class Program
{
static async Task Main(string[] args)
{
string urlToCheck = "https://test.com";
UrlChecker urlChecker = new UrlChecker();
bool isValid = await urlChecker.CheckUrl(urlToCheck);
if (isValid)
{
Console.WriteLine("URL is valid and exists.");
}
else
{
Console.WriteLine("URL is not valid or doesn't exist.");
}
}
}