check URL exists or throws page not found message in asp.net - asp.net

I want to validate an url, whether it exists or throwing page not found error. can anyone help me how to do it in asp.net.
for e.g., my url may be like http://www.stackoverflow.com or www.google.com i.e., it may contain http:// or may not. when i check, it should return the webpage valid if exists or page not found if doesnot exists
i tried HttpWebRequest method but it needs "http://" in the url.
thanks in advance.

protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}

Try this
using System.Net;
////// Checks the file exists or not.
bool FileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if it Exist
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false. So the URL is Not Exist
return false;
}
}
Hope I Helped

Related

How to pass array to php url from c#? [duplicate]

Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL

Check a URL exists in ASP.NET with timeout

I have 5 sites and a domain like x.company.com.
I want use x.company.com as a load balancer to send users to x1 .. x5 sub domains.
before send users to special sub domain I want check sub domain services is alive.
Now I do these but check of sub domain maybe too late to response, so I want
check sub domain service for 2 second and if no responses go to check another sub domain.
How to do that with c# asp.net?
or anybody have better suggestions for this balancing?
My code for check URL is:
private bool HttpExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
ServicePointManager.Expect100Continue = false;
request.Proxy = WebRequest.DefaultWebProxy;
request.Proxy = null;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}

Url Redirection error if url contains reserved characters

I am trying to access particular url
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(new AuthScope("abc.com", 443),
new UsernamePasswordCredentials("user", "Passwd"));
HTTPHelper http = new HTTPHelper(httpclient);
http.get("http://abc.com/**aaa**/w/api.php?param=timestamp%7Cuser&format=xml");
where %7C= |
which is redirecting me to the following url internally
http://abc.com/**bbb**/w/api.php?param=timestamp%257Cuser&format=xml
and because of that I am not able to get the correct output...
| ==>%7C
%==> %25
%7C == %257C
I want query to be timestamp|user
but because of circular redirection it is changed into timestamp%7Cuser
Is there any way to avoid this??
I wrote my own Custom Redirect Strategy also
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect = false;
try {
isRedirect = super.isRedirected(request, response, context);
LOG.info(response.getStatusLine().getStatusCode());
LOG.info(request.getRequestLine().getUri().replaceAll("%25", "%"));
} catch (ProtocolException e) {
e.printStackTrace();
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return isRedirect;
}
});
But I am not sure how to replace %25C with %7C from redirected url
It looks like the site's URL rewrite rules are simply broken. If it's not your site, you may want to contact its maintainers and inform them about the issue.
In the mean time, is there some reason why you can't simply use the target URLs (i.e. http://abc.com/**bbb**/w/api.php?...) directly, avoiding the redirect?
Does just http.get("http://abc.com/**aaa**/w/api.php?param=timestamp|user&format=xml");
work?
What's your meaning "redirecting me to the following url internally"? It's like that your url are encoded again. Can you post code in HTTPHelper? My below test code work correctly.
Client Code:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://localhost:8080/test/myservlet?param=timestamp%7Cuser&format=xml");
client.execute(get);
Servlet Code:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("param"); //get timestamp|user
String format = request.getParameter("format");
}

Asp.net HttpWebResponse - how can I not depend on WebException for flow control?

I need to check whether the request will return a 500 Server Internal Error or not (so getting the error is expected). I'm doing this:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
But when I get the 500 Internal Server Error, a WebException is thrown, and I don't want to depend on it to control the application flow - how can this be done?
I think this MSDN articles will help you:
http://msdn.microsoft.com/en-us/library/system.net.webexception.status.aspx
Indeed, given the example at msdn, there is no way to not depend on the exception for control flow. Here's the example they give:
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
Apparently, sometimes you do have to go down that route. Ah, well.

Google Checkout HTTP Post with ASP.net

I have 2 pages I created in ASP.net(C#). The first one(called shoppingcart.asp) has a buy it now button. The second one(called processpay.asp) just waits for google checkout to send an HTTP request to it to process the payment. What I would like to do send a post statement to google checkout with a couple of variables that I want passed back to processpay.asp(ie clientid=3&itemid=10), but I don't know how to format the POST HTTP statement or what settings I have to change in google checkout to make it work.
Any ideas would be greatly appreciated.
Google Checkout has sample code and a tutorial on how to integrate it with any .NET application:
Google Checkout API - Google Checkout Sample Code for .NET
Make sure to check the section titled: "Integrating the Sample Code into your Web Application".
However, if you prefer to use a server-side POST, you may want to check the following method which submits an HTTP post and returns the response as a string:
using System.Net;
string HttpPost (string parameters)
{
WebRequest webRequest = WebRequest.Create("http://checkout.google.com/buttons/checkout.gif?merchant_id=1234567890");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException e)
{
// handle e.Message
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
// get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{
return null;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException e)
{
// handle e.Message
}
return null;
}
Parameters need to be passed in the form: name1=value1&name2=value2
The code will likely end up looking something like this:
GCheckout.Checkout.CheckoutShoppingCartRequest oneCheckoutShoppingCartRequest =
GCheckoutButton1.CreateRequest();
oneCheckoutShoppingCartRequest.MerchantPrivateData = "clientid=3";
GCheckout.Checkout.ShoppingCartItem oneShoppingCartItem =
new GCheckout.Checkout.ShoppingCartItem();
oneShoppingCartItem.Name = "YourProductDisplayName";
oneShoppingCartItem.MerchantItemID = "10";
oneCheckoutShoppingCartRequest.AddItem(oneShoppingCartItem);
Yesterday I used http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx to send the post data and it works fine

Resources