我可能走错了路,因为我没有网络请求方面的经验,所以请容忍我。
我试图执行以下代码:
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))当URI可用时,这很好。但是,如果没有(即。如果相应的服务没有运行并且没有公开相关的数据),我将得到以下错误消息:
SocketException发生了:由于目标机器主动拒绝连接,所以无法建立连接。
因此,我试图按如下方式实现try/catch块:
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那不起作用。VB.Net仍然不显示消息框。所以,我尝试了其他的方法:
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也不起作用。我一定是不正确地处理这个问题。有人能告诉我什么是正确的方法吗?在运行DownloadStringAsync函数之前,是否有一种首先检查数据是否存在的方法?
谢谢!
编辑:将上下文添加到Vincent的答案下的讨论中,下面是我的代码。只有一个表格。
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发布于 2018-02-17 15:37:15
WebClient.DownloadStringAsync()方法不抛出SocketException,而是抛出WebException (可能将其内部异常设置为SocketException)。
例外情况 WebException 将BaseAddress和地址组合在一起形成的URI无效。 -或者- 下载资源时出错。
大多数情况下,SocketException只由原始套接字引发。然后,System.Net命名空间的成员通常将它们包装在一个WebException中。
因此,要修复您的代码:
Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
Catch ex As System.Net.WebException
MessageBox.Show("Error. Service is not running. No data can be extracted.")
End Try注意:我转而使用MessageBox.Show(),因为MsgBox()已经过时,并且只存在于与VB6的向后兼容性。
但是,最佳实践是添加另一个Catch语句,该语句也捕获所有其他异常,这样您的应用程序就不会出现崩溃。
您还应该记录来自WebException的错误消息,因为它可能是出于其他原因而抛出的,而不仅仅是不可用的端点。
Try
webClient.DownloadStringAsync(New Uri("http://localhost:8115/"))
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 Tryhttps://stackoverflow.com/questions/48842373
复制相似问题