Unable to catch 404 error on HttpWebRequest response - vb.net

Trying the below code to catch 404 error page but seems not to work, I mean 404 error doesn't display in response. The response only displays if the file exists (200 http code) !! but if the file doesn't exist (404) like in the below example, not msgbox displays, and the exception also doesn't display anything that's why I insert a msgbox in there.
If you try to take out these "111" from the "index.html" and run it, it'll display 200 http code well.
Using VS 2013, don't know, if it's a bug, or because I'm going through a proxy.
Will check it later from home for proxy as at work we're using proxy server.
Can anybody help !!
Try
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://www.cisco.com/c/en/us/support/index111.html")
Dim response As System.Net.HttpWebResponse = request.GetResponse
If response.StatusCode = Net.HttpStatusCode.OK Then
MsgBox("File exist on Server")
MsgBox(response.StatusCode) '200 HTTP CODE
'Trying to catch 404 error here
ElseIf response.StatusCode = Net.HttpStatusCode.NotFound Then
MsgBox("FILE NOT FOUND ON THE SERVER")
MsgBox(response.StatusCode)
Else
MsgBox("NO FILE on the server")
End If
Catch ex As Exception
'Msgbox("Error")
End Try

request.GetResponse will throw an exception when the request fails, for whatever reason.
There is a Response object in the exception through, on which you can ask what the status code was. Check ex.Response.StatusCode in your Catch block.

Related

How do I check the response code of multiple websites?

i'm a new in VB and i'm trying to make a program that gets and
displays the HTTP response code of a multiple website.
something like:
http response code of target website www.example.com : 200 OK
http response code of target website www.abc2.com : 405 Method Not Allowed
http response code of target website www.testing2.com : 404 Not Found
http response code of target website www.last23.com : 408 RequestTimeout
etc.
I Tried to code it myself but i couldn't , And i also tried to find
online but i didn't found something that works.
i found this code but I think I need a loop to check multiple sites
can you help me with that? how can create loop and check status code
for multiple websites
Public Shared Function GetResponse(uri As String) As HttpStatusCode
Dim req As HttpWebRequest = WebRequest.Create(uri)
Dim resp As HttpWebResponse
Try
resp = DirectCast(req.GetResponse(), HttpWebResponse)
Catch ex As WebException
resp = DirectCast(ex.Response, HttpWebResponse)
End Try
Return resp.StatusCode
End Function
Using the GetResponse function you've already got it's quite simple
Dim sites as new List(of String)
sites.Add("www.example.com")
sites.Add("www.abc2.com")
sites.Add("www.testing2.com")
sites.Add("www.last23.com")
For Each site As String In sites
Dim siteResponse as String = GetResponse(site)
Console.WriteLine("http response code of target website " & site & " " & siteResponse)
Next
That's just off the top of my head so might have a couple gaffs in it

HTTP response code checker in VB?

i'm a new in VB and i'm trying to make a program that
gets and displays the HTTP response code of a website.
something like:
http response code of target website www.example.com : 200 OK
etc.
I Tried to code it myself but i couldn't , And i also tried to find online but i didn't
found something that works.
i found this http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.statuscode(v=vs.110).aspx
i tried that and that didn't really helped me.
Anyone has a code that does that?
I'm a C# guy, so this might not be perfect, but I believe this should do it.
Public Shared Function GetResponse(uri As String) As HttpStatusCode
Dim req As HttpWebRequest = HttpWebRequest.CreateHttp(uri)
Dim resp As HttpWebResponse
Try
resp = DirectCast(req.GetResponse(), HttpWebResponse)
Catch ex As WebException
resp = DirectCast(ex.Response, HttpWebResponse)
End Try
Return resp.StatusCode
End Function

Check if folder on web exists or not

I'm creating desktop aplication and when I write a username in TextBox1 and on Button1.Click event it should check does folder on web exists.
As far I've tried this:
username = Me.TextBox1.Text
password = Me.TextBox2.Text
Dim dir As Boolean = IO.Directory.Exists("http://www.mywebsite.com/" + username)
If dir = true Then
Dim response As String = web.DownloadString("http://www.mywebsite.com/" + username + "/Password.txt")
If response.Contains(password) Then
MsgBox("You've logged in succesfully", MsgBoxStyle.Information)
Exit Sub
Else
MsgBox("Password is incorect!")
End If
Else
MsgBox("Username is wrong, try again!")
End If
First problem is that my boolean is giving FALSE as answer (directory exists for sure and all permissions are granted to see folder). I tried to solve that with setting dir = false and after that I go into first IF (but that's not what I want, since it should be TRUE, not FALSE)
There we come to second problem, in this line: Dim response As String=web.DownloadString("http://www.mywebsite.com/" + username + "/Password.txt") I get this error message: The remote server returned an error: (404) Not Found.
Anyone more experienced with this kind of things who can help me?
IO.Directory.Exists will not work in this case. That method only works to check for a folder on a disk somewhere (locally or network) ; you can't use it to check for the existence of a resource over HTTP. (i.e a URI)
But even if it did work this way, it's actually pointless to call it before attempting to download - the method DownloadString will throw an exception if something goes wrong - as you have seen, in this case it's telling you 404 Not Found which means "This resource does not exist as far as you are concerned". **
So you should try/catch the operation, you need to catch exceptions of type WebException, cast its Response member to HttpWebException, and check the StatusCode property.
An good example (albeit in C#) is here
** I say "as far as you are concerned" because for all you know, the resource may very well exist on the server, but it has decided to hide it from you because you do not have access to it, etc, and the developer of that site decided to return 404 in this case instead of 401 Unauthorised. The point being that from your point of view, the resource is not available.
Update:
here is the code from the answer I linked to, translated via this online tool because my VB is dodgy enough :). This code runs just fine for me in LinqPad, and produces the output "testlozinka"
Sub Main
Try
Dim myString As String
Using wc As New WebClient()
myString = wc.DownloadString("http://dota2world.org/HDS/Klijenti/TestKlijent/password.txt")
Console.WriteLine(myString)
End Using
Catch ex As WebException
Console.WriteLine(ex.ToString())
If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then
Dim resp = DirectCast(ex.Response, HttpWebResponse)
If resp.StatusCode = HttpStatusCode.NotFound Then
' HTTP 404
'the page was not found, continue with next in the for loop
Console.WriteLine("Page not found")
End If
End If
'throw any other exception - this should not occur
Throw
End Try
End Sub
Hope that helps.

VB.NET | HttpWebRequest, How to see if the host is online?

I am coding a whitelist for my application in VB.NET.
I am using the HttpWebRequest Method and HttpWebResponse.
If the Whitelist Host is down, the whitelist is bypassed and the program is available to anyone which is a vulnerability.
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
End Try
Return S
End Function
I want to give the user an error if the website is down, any ideas?
Regards.
What is your error condition? This function alone doesn't prevent anything from happening in the event of an exception. The function still exits with returning a string. So any consuming code would have to look for error conditions and handle them accordingly.
If the request fails, you should meaningfully handle the exception. Two ideas off the top of my head would include:
1) Let the exception bubble up the stack:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Return S
End Function
This would make the attempt to contact the host and, if that attempt failed, throw an exception instead of return a string.
2) Throw a custom exception:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
Throw New SomeCustomException(String.Format("Unable to contact host: {0}", PageURL), ex)
End Try
Return S
End Function
This would provide a more targeted exception instead of whatever comes out of the response reader, would provide useful runtime information about the error for logging and analysis (namely the runtime value of the PageURL), and takes a step toward hiding the implementation details from code outside of this object (since that code doesn't really care about the HttpWebRequest and HttpWebResponse, it just wants to know if the URL is good or not).
Remember that throwing an exception is a perfectly acceptable exit path for a function. It doesn't always have to return a value. An exception is an appropriate way of indicating an error condition. Your current implementation, however, "swallows" the exception and provides no indication to the consuming code that anything went wrong. Instead it returns a "magic value" of String.Empty which consuming code may or may not ignore.
Change your exception handler. The correct way to do this is to just try the request and handle the exception if it fails.

VB 2010 Download file and if 404 happen ignore error

I'm beginner on VB 2010
and I wanna write an app that can downloads file
My question is:
If it gives me 404 or 403 or whatever, I wanna let the app ignore that message, instead of a webexception error
Note: I've already know how to download file with VB
If you want to ignore some errors, but throw others, you can use the HTTP Response status code to decide what to do:
Try
Dim wc As New System.Net.WebClient()
wc.DownloadFile("http://www.google.com/somefilethatdoesntexist.txt", "C:\temp\somefilethatdoesntexist.xls")
Catch ex As System.Net.WebException
Dim response As System.Net.HttpWebResponse = ex.Response
Select Case response.StatusCode
Case System.Net.HttpStatusCode.NotFound, System.Net.HttpStatusCode.Unauthorized
' Do something with not founds or unauthorized
Console.WriteLine("Ignoring : " & ex.ToString())
Case Else
Console.WriteLine(ex.ToString())
Throw ex
End Select
End Try
You should not swallow errors - you should try to deal with it in some fashion even if it is just to log it.
You need to catch the WebException and then handle it by perhaps logging the error and then do not rethrow it.
Try
'Download file...
Catch ex As WebException
Logger.WriteError(ex)
End Try