Currently in my website, I need to verify a URL param to ensure that it's a valid and it's an accessible URL. I'm using the code below:
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null) return false;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
I had deployed the website in my server and so far every work fine, no issue with the URL verification.
Now I had published the same application in client server. But the URL verification always failed even just for http://www.google.com. I have log file that record the failure of verification and the value.
I retrieve all those URL value in client site and test again in my own server but no issue at all.
That's why I suspect that it's not code issue but environment issue.
Any advice on what to check?
Thanks
Try the following. If there is an exception, hopefully it will give you a clue on the issue you are having.
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null) return false;
request.AllowRedirect = false; // default: true
request.Method = "GET"; // this is the default
try
{
var response = (HttpWebResponse)request.GetResponse());
if (res.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
}
catch (Exception ex)
{
return ex.Message;
}
Related
how to Verify where website is using https, a secure communication protocol/not.
like if i give www.facebook.com it should show https protected or not.im getting error in second line.im getting false even though site is https
checkSecured();
private void checkSecured()
{
string url = txturl.Text.Trim();
var uri = new Uri("https://www.facebook.com");
var requestType = uri.Scheme;
var value= HttpContext.Current.Request.IsSecureConnection;
}
there are many sites which works on both http and https, some works on http and some on https.
So in your url check twice
1) If http://+url is valid or not
2) if https://+url is valid or not.
Then you can get the result.
private bool RemoteFileExists(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 TRUE if the Status code == 200
response.Close();
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
from: C# How can I check if a URL exists/is valid?
You can use the below line of code to check if the connection is secured or not.
HttpContext.Current.Request.IsSecureConnection
I am trying to swap my website over to consuming the new Twitter 1.1 API with uses OAuth 1.0a. I am able to get the correct response using a REST client and I am now trying to duplicate that on my website using c#.
I have constructed my headers the appropriate way and I have verified that they are in the correct format for what Twitter is looking for.
The issue I am having is that I do not think I am actually sending the request. I say this because my application returns almost instantly. The request should take a second or so to send at least, and my response has totally empty, with no 401 or 400 status code.
Below I have the code that actually sends the request. I am actually sending the request and if so why am I not getting any status code or anything.
Thanks in advance for the help.
//string url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=MYSCREENNAME&count=2";
string url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
try {
var response = webRequest.GetResponse() as HttpWebResponse;
if (response != null && response.StatusCode != HttpStatusCode.OK) {
lblresponse.InnerText = "The request did not complete and returned status code: {0} " + response.StatusCode;
}
if (response != null) {
var reader = new StreamReader(response.GetResponseStream());
reader.ReadToEnd();
lblresponse.InnerText += "success";
}
} catch {
lblresponse.InnerText += "fail";
}
So yeah this code goes straight to the catch block. My thoughts are I am not actually sending the request, since it takes no time to happen. I know there are some libraries designed to make this easier but I would much rather learn how to do it myself (with the help of you guys).
Thanks.
The request is going to throw an exception in the case of a 400 or 401. So catch System.Web.Exception in the catch block to see if there's a 400 or 401.
catch(System.Web.Exception ex) {
var errorReponse = (HttpWebResponse)ex.Response;
var statusCode = errorReponse.StatusCode;
lblresponse.InnerText += "fail";
}
I am getting The remote server returned an error: (400) Bad Request error while running the following code.
I am trying to upload xml file on the http server.
My xml file contains tag for the username,password and domain and when i am trying to connect is manually i am able to connect it,but using same credentials when i am trying to connect it through this code, i am getting 400 Bad Request error.
Please suggest me how to overcome this issue.
Thanks
`
public static void UploadHttp(string xml)
{
string txtResults = string.Empty;
try
{
string url = "http://my.server.com/upload.aspx ";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.KeepAlive = false;
request.SendChunked = true;
request.AllowAutoRedirect = true;
request.Method = "Post";
request.ContentType = "text/xml";
var encoder = new UTF8Encoding();
var data = encoder.GetBytes(xml);
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse response = null;
response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var str = reader.ReadToEnd();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse err = ex.Response as HttpWebResponse;
if (err != null)
{
string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
}
}
else
{
}
}
catch (Exception ex)
{
txtResults = ex.ToString();
}
}`
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
400 Bad request Error will be thrown due to incorrect authentication entries.
Check if your API URL is correct or wrong. Don't append or prepend spaces.
Verify that your username and password are valid. Please check any spelling mistake(s) while entering.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
What type of authentication do you use?
Send the credentials using the properties Ben said before and setup a cookie handler.
You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
//use "ASCII" or try with another encoding scheme instead of "UTF8".
using (StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.UTF8))
{
postStream.Write(postData);
postStream.Close();
}
I am validating a regular URL as follows:
private static bool IsUrlAvailable(string url)
{
if ((string.IsNullOrEmpty(url.Trim()) == true) ||
(url.Trim().ToLower().Equals("http://")) ||
(url.Trim().ToLower().Equals("https://")))
{
return false;
}
if (!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
{
url = "http://" + url;
}
try
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 15000;
req.Method = "HEAD";
using (var rsp = (HttpWebResponse)req.GetResponse())
{
if (rsp.StatusCode == HttpStatusCode.OK)
{
return true;
}
}
}
catch (Exception ex)
{
// Eat it because all we want to do is return false
}
// Otherwise
return false;
}
But since I am using a WebRequest.Create, authenticated SharePoint urls on the intranet are failing validation because of permission denied (404) error. Now I know we can validate it using SPSite.Exists or OpenWeb but these are only available in microsoft.sharepoint.dll and I was wondering if there is a way of doing this without using this DLL?
404 is not permission denied... but file-not-found. So you may indeed hit non-existing Url.
You need to pass credentials with your request
WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Side note: please do not "eat all exceptions" - there is very small set of exceptions that are interesting in case of making WebRequests which you can find in article about HttpWebRequest.GetResponse (you likley should only handle WebException).
I want my program in C# to check if a website is online prior to executing, how would I make my program ping the website and check for a response in C#?
A Ping only tells you the port is active, it does not tell you if it's really a web service there.
My suggestion is to perform a HTTP HEAD request against the URL
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("your url");
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
try {
response = request.GetResponse();
// do something with response.Headers to find out information about the request
} catch (WebException wex)
{
//set flag if there was a timeout or some other issues
}
This will not actually fetch the HTML page, but it will help you find out the minimum of what you need to know. Sorry if the code doesn't compile, this is just off the top of my head.
You have use System.Net.NetworkInformation.Ping see below.
var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.google.com");
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
return;
Small remark for Digicoder's code and complete example of Ping method:
private bool Ping(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3000;
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
using (var response = request.GetResponse())
{
return true;
}
}
catch
{
return false;
}
}
if (!NetworkInterface.GetIsNetworkAvailable())
{
// Network does not available.
return;
}
Uri uri = new Uri("http://stackoverflow.com/any-uri");
Ping ping = new Ping();
PingReply pingReply = ping.Send(uri.Host);
if (pingReply.Status != IPStatus.Success)
{
// Website does not available.
return;
}
The simplest way I can think of is something like:
WebClient webClient = new WebClient();
byte[] result = webClient.DownloadData("http://site.com/x.html");
DownloadData will throw an exception if the website is not online.
There is probably a similar way to just ping the site, but it's unlikely that the difference will be noticeable unless you are checking many times a second.