REST Web服务:如何从Web服务获取zip文件到客户端

时间:2014-05-28 08:14:32

标签: vb.net web-services rest

我试图创建一个函数来下载一个zip文件,该文件来自REST WebService,其客户端调用Web服务(都是用VB.Net编写的)。 WebService方面我有以下代码:

Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
    Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
    Dim length As Integer = CType(f.Length, Integer)
    WebOperationContext.Current.OutgoingResponse.ContentLength = length
    Dim buffer As Byte() = New Byte(length) {}
    Dim sum As Integer = 0
    Dim count As Integer
    While ((count = f.Read(buffer, sum, length - sum)) > 0)
        sum += count
    End While
    f.Close()
    Dim mimeType = ""
    WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
    Return New MemoryStream(buffer)
End Function

客户端我有以下代码:

sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False

Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())

响应有ContentLenght = 242699,所以似乎收到了流,但StIn似乎是空的。解决问题的最佳解决方案是什么?

1 个答案:

答案 0 :(得分:2)

我想您已经忘记从StreamReader读取文件了。

        Dim inSaveFile As String = "C:\stream\test.doc"

        If Dir(inSaveFile) <> vbNullString Then
            Kill(inSaveFile)
        End If

        Dim swFile As System.IO.StreamWriter

        Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)

        swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)

        Dim response1 As System.Net.HttpWebResponse = req.GetResponse()

        Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)

        Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)

        swFile.WriteLine(stIn.ReadToEnd)

        swFile.Close()

        fs.Close()