How to check particular url is exist or not with the help of HttpWebResponse ?

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

Let’s see,

 

How to check particular url is exist or not with the help of HttpWebResponse 

 

[Route(“Check”)]
public HttpResponseMessage Check(string appUrl)
{

//Set as below
appUrl=https://sandippatil.com/Downloads/Training ManualHTML.pdf”;

Uri destURL = new Uri(appUrl);
HttpWebRequest request = HttpWebRequest.CreateHttp(destURL);
request.Method = “HEAD”;
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
helpEnabled = true;
}
}
catch (Exception ex)
{
helpEnabled = false;
}
HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;
}

 

If doesn’t exists it will throws an exception as shown in below Image.

sk2

 

Another solution is

var appUrl=”https://sandippatil.com/Downloads/Training ManualHTML.pdf”;

bool urlExists;

WebRequest webRequest = WebRequest.Create(appUrl);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
urlExists= true;
}
catch //If exception thrown then couldn’t get response from address
{
urlExists= false;
}
HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;

 

Working code in WebAPI controller is

 

[Route(“CheckHelpButtonPermission”)]
public HttpResponseMessage CheckHelpButtonPermission(string appUrl)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(appUrl);
webRequest.Method = “GET”;

string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();

using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
helpEnabled = true;
}
}
catch (System.Net.WebException ex)
{
helpEnabled = false;
}

HttpResponseMessage resp;
resp = Request.CreateResponse<bool>(HttpStatusCode.OK, helpEnabled);
return resp;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s