使用请求超时(Net.WebClient)

时间:2019-02-12 15:30:41

标签: vb.net webclient

您可以使用以下方法为请求设置超时

Net.WebClient()

我知道WebRequest可以实现,但是我想使用WebClient。

编辑:我创建了一个名为WbClnt的新类,其中包含以下代码:

Imports System.Net
Public Class WbClnt
    Inherits WebClient
    Protected Overrides Function GetWebRequest(ByVal uri As Uri) As WebRequest
        Dim w As WebRequest = MyBase.GetWebRequest(uri)
        w.Timeout = 5000
        Return w
    End Function
End Class

但是,我可能无法使用WbClnt.GetWebRequest从我的主窗体中调用此函数,

1 个答案:

答案 0 :(得分:2)

根据以上所有评论,这是我建议做的一个简单实现。

Imports System.Net

Public Class MyPatientlyWebClient
    Inherits WebClient

#Region "Variables"
    Private ReadOnly _timeOut As Integer = 100000
#End Region

#Region "Properties"

    ''' <summary>
    ''' Determine's how to long to wait for request.
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property HowLongToWait
        Get
            Return _timeOut
        End Get
    End Property
#End Region

#Region "Constructors"
    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal timeOut As Integer)
        MyBase.New()
        If timeOut <= 0 Then timeOut = 100000
        _timeOut = timeOut
    End Sub

#End Region

#Region "Overrides"

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        w.Timeout = HowLongToWait
        Return w
    End Function

#End Region

End Class

使用

Dim myPaWebClient As New MyPatientlyWebClient(120000)
Dim str As String = myPaWebClient.DownloadString("https://www.google.com")

您可以根据需要设置属性;需要更改ReadOnly,我为您快速准备了一些内容。