开发者

Visual Basic set User Agent with ReadXml

开发者 https://www.devze.com 2023-04-01 09:22 出处:网络
I\'m trying to set the user agent for a request with XmlRead. I googled a lot about this and couldn\'t find the answer. Here is my chunk of code:

I'm trying to set the user agent for a request with XmlRead. I googled a lot about this and couldn't find the answer. Here is my chunk of code:

 Dim RssData As DataSet
        Dim Title As String
        Dim Url As String
        Dim Stream As String
        Dim buffer As Integer
        RssData = New DataSet()
        RssData.ReadXml("http://localhost/user_agent.php")
        buffer = 0
        For Each RssRow As DataRow In RssData.Tables("entry").Rows
            Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
            Stream += Title & vbCrLf

        Next
        LinkLabel3.Text = Stream

        For Each RssRow As DataRow In RssData.Tabl开发者_如何学编程es("entry").Rows
            Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
            Url = RssRow.Item("url").ToString
            LinkLabel3.Links.Add(buffer, Title.Length, Url)
            buffer = buffer + Title.Length + 2
        Next


The part of the code that actually performs the web request is buried pretty deep so you'd have to inherit a bunch of code to do what you asked for. Instead, let me suggest a different path, download the XML on your own with code that's easy to set that header, and then load that into the dataset. The WebClient class lets you set arbitrary headers and has a simple DownloadString method. Once you've got that you can wrap it in a MemoryStream and pass that into ReadXml(). (I couldn't find a way to read the XML as a string, that's why I was forced to read it as Stream.)

    ''//Will hold our downloaded XML
    Dim MyXml As String

    ''//Create a webclient to download our XML
    Using WC As New System.Net.WebClient()
        ''//Manually set the user agent header
        WC.Headers.Add("user-agent", "your user agent here")
        ''//Download the XML
        MyXml = WC.DownloadString("http://localhost/user_agent.php")
    End Using
    ''//Create our dataset object
    Dim RssData As New DataSet()
    ''//There is no direct method to load XML as a string (at least that I could find) so we will
    ''//    convert it to a byte array and load it into a memory stream
    Dim Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(MyXml)
    Using MS As New System.IO.MemoryStream(Bytes)
        ''//Load the stream into the reader
        RssData.ReadXml(MS)
    End Using

    ''//Your code continues normally here
0

精彩评论

暂无评论...
验证码 换一张
取 消