I'm probably going about this the wrong way, as I have no experience with web requests, so please bear with me.
I'm trying to execute the following code:
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
This works fine when the URI is available. However, if it is not available (ie. if the respective service is not running and is not exposing the relevant data), I get the following error message:
SocketException occurred: No connection could be made because the target machine actively refused it.
So, I tried to implement a try/catch block as follows:
If Not webClient.IsBusy Then
Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
Catch ex As Sockets.SocketException
MsgBox("Error. Service is not running. No data can be extracted.")
End Try
End If
That did not work. VB.Net still does not display the message box. So, I tried something else:
If Not webClient.IsBusy Then
Dim req As System.Net.WebRequest
req = System.Net.WebRequest.Create(New Uri("http://localhost:8115/"))
Dim resp As System.Net.WebResponse
Dim ready As Boolean = False
Try
resp = req.GetResponse
resp.Close()
ready = True
Catch ex As Sockets.SocketException
MsgBox("Error. Service is not running. No data can be extracted.")
End Try
If ready Then
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
ready = False
End If
End If
It also doesn't work. I must be approaching this problem incorrectly. Can someone show me what the correct way of doing this is? Is there a way of first checking if the data exists, before running the DownloadStringAsync function?
Thanks!
Edit: To add context to the discussion under Visual Vincent's answer, here is what my code looks like. Just a single form.
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim webClient As New System.Net.WebClient
Try
WebClient.DownloadStringAsync(New Uri("http://localhost:8115"))
Catch ex As System.Net.Sockets.SocketException
MessageBox.Show("Error")
Catch ex As System.Net.WebException
MessageBox.Show("Error. Service is not running. No data can be extracted.")
Catch ex As Exception
MessageBox.Show("An error occurred:" & Environment.NewLine & ex.Message)
End Try
End Sub
End Class