VB.NET HttpWebRequest以块的形式下载文件

时间:2016-07-25 01:39:58

标签: c# vb.net httpwebrequest httpwebresponse

我正在寻求以下方面的帮助:

在我的Windows窗体应用程序中,我下载了我控制的远程服务器上的文件。我的代码如下:

disk0_usedpc

问题是,如果下载未在指定时间内完成(带有超时设置的注释行),我们将收到超时异常。如果下载被分块,我会看到驱动器上的文件大小增加。但是,不是这样,只有当响应完全完成时才会出现文件。

在服务器端,我使用response.outputstream.write方法发送块。

如何处理慢速连接的较大文件上的时间?

1 个答案:

答案 0 :(得分:0)

我发现,只有在发送POST请求时才会发生这种情况。我将params更改为URL查询字符串,现在可以使用chunked下载。

    Public Shared Function DownloadFileWithQueryString(ByVal httpPath As String, ByVal storePath As String, querystring As String) As String
    Try
        Dim theResponse As HttpWebResponse
        Dim theRequest As HttpWebRequest
        Dim fullurl As String = httpPath & "?" & querystring
        theRequest = HttpWebRequest.Create(fullurl)


        If My.Settings.ProxyURL <> "" Then
            Dim prx As New WebProxy(My.Settings.ProxyURL)
            theRequest.Proxy = prx
        End If




        theResponse = theRequest.GetResponse

        Dim length As Double = theResponse.ContentLength




        Dim writeStream As New IO.FileStream(storePath, IO.FileMode.Create)


        Dim nRead As Integer

        Dim readBytes(4095) As Byte
        Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)



        Do Until bytesread = 0



            'speedtimer.Start()


            nRead += bytesread



            writeStream.Write(readBytes, 0, bytesread)


            bytesread = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
        Loop

        'Close the streams
        theResponse.GetResponseStream.Close()
        writeStream.Close()


        Return "OK"
    Catch ex As Exception
        Return ex.Message
    End Try
End Function
相关问题