如何使用 vb.NET 从 URL 读取 XML 数据并保存
朋友们,我能够通过单个字节获取 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
Friends, I am able to get XML file by sing bytes, perhaps which is getting some problem. Can u suggest me alternate method to do the same thing to save XML file?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用
WebClient
类及其DownloadFile
方法?看起来容易多了......这是用 C# 编写的,但是将其转换为 VB.NET 应该没有问题:
然后就完成了!
马克
Why not just use the
WebClient
class and itsDownloadFile
method?? Seems a lot easier....This is in C#, but you should have no trouble converting that to VB.NET:
and you're done!
Marc
考虑使用 XMLTextReader。此示例只是将整个 XML 加载到字符串中,但显然您可以将其写入文件:
Consider using XMLTextReader. This example just loads the entire XML into a string, but obviously you could write it to a file instead:
如果服务将请求发送到我们的 URL 怎么办?我如何调整它来读取他们发送的http流?经历了这么艰难的时光......(我应该做一个单独的线程吗?抱歉。)
What if the service is sending the request to our URL? How do I adjust this to read the http stream they send? Having such a hard time... (Should I do a separate thread? Sorry.)