【问题标题】:How can I change the time limit for webClient.UploadData()?如何更改 webClient.UploadData() 的时间限制?
【发布时间】:2010-11-17 07:13:54
【问题描述】:

我正在使用WebClient.UploadData() 在 Java 服务器上发帖。如何延长时间限制? (每次我尝试进行调试时都会超时)

【问题讨论】:

    标签: c# .net web-services webclient


    【解决方案1】:

    所以对于那些用 VB 编写代码的人...

    Public Class WebClientExtended
        Inherits WebClient
        Public Property Timeout() As Integer
            Get
                Return m_Timeout
            End Get
            Set(value As Integer)
                m_Timeout = value
            End Set
        End Property
        Private m_Timeout As Integer
    
        Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
            Dim request = MyBase.GetWebRequest(address)
            request.Timeout = Timeout
            Return request
        End Function
    End Class
    
    Function UploadFile(ByVal URL As String, ByVal FilePath As String, ByVal FileName As String)
    
        'Call API to Upload File
        Dim myWebClient As New WebClientExtended
        myWebClient.Timeout = 10 * 60 * 1000
        Dim responseArray As Byte()
        Dim responseString As String = ""
    
        Try
            responseArray = myWebClient.UploadFile(URL, FilePath + "/" + FileName)
            responseString = System.Text.Encoding.ASCII.GetString(responseArray)
        Catch ex As Exception
            responseString = "Error: " + ex.Message
        End Try
    
        Return responseString
    
    End Function
    

    【讨论】:

      【解决方案2】:

      WebClient 没有 timeout 属性,但是可以从 WebClient 继承以授予对使用的内部 WebRequest 的 Timeout 的访问权限:

       public class WebClientEx : WebClient
       {
           public int Timeout {get; set;}
      
           protected override WebRequest GetWebRequest(Uri address)
           {
              var request = base.GetWebRequest(address);
              request.Timeout = Timeout;
              return request;
           }
       }
      

      用法:

       var myClient = new WebClientEx();
       myClient.Timeout = 900000 // Daft timeout period
       myClient.UploadData(myUri, myData);
      

      【讨论】:

      • 很好的答案。仅供参考,我使用了它,它也适用于 WebClient.UploadValues()
      • 太好了,这很有帮助!
      猜你喜欢
      • 2013-09-17
      • 2019-07-02
      • 2011-02-16
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多