如何使用vb.NET从URL读取XML数据并保存

pra*_*kar 2 vb.net httprequest

朋友们,我能够通过单字节获取XML文件,也许这会产生一些问题.您可以建议我使用替代方法来保存XML文件吗?

  Try
        Dim strUrl As String = "http://example.com" 
        Dim wr As HttpWebRequest = CType(WebRequest.Create(strUrl), HttpWebRequest)
        Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
        ws.ContentType = "UTF-16"
        Dim str As Stream = ws.GetResponseStream()
        Dim inBuf(100000) As Byte
        Dim bytesToRead As Integer = CInt(inBuf.Length)
        Dim bytesRead As Integer = 0
        While bytesToRead > 0
            Dim n As Integer = str.Read(inBuf, bytesRead, bytesToRead)
            If n = 0 Then
                Exit While
            End If
            bytesRead += n
            bytesToRead -= n
        End While
        Dim fstr As New FileStream("c:/GetXml.xml", FileMode.OpenOrCreate, FileAccess.Write)
        fstr.Write(inBuf, 0, bytesRead)
        str.Close()
        fstr.Close()
    Catch ex As WebException
        Response.Write(ex.Message)
    End Try
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 6

为什么不只是使用WebClient类及其DownloadFile方法?似乎更容易....

这是在C#中,但是将它转换为VB.NET应该没有问题:

WebClient wc = new WebClient();
wc.DownloadFile("http://xyz", @"C:\getxml.xml");
Run Code Online (Sandbox Code Playgroud)

你完成了!