0

我正在尝试为带有 XmlRead 的请求设置用户代理。我对此进行了很多搜索,但找不到答案。这是我的代码块:

 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.Tables("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
4

1 回答 1

1

实际执行 Web 请求的代码部分被埋得很深,因此您必须继承一堆代码才能完成您的要求。相反,让我建议一条不同的路径,使用易于设置该标头的代码自行下载 XML,然后将其加载到数据集中。该类WebClient允许您设置任意标题并具有简单的DownloadString方法。一旦你得到它,你可以将它包装在 a 中MemoryStream并将其传递给ReadXml(). (我找不到将 XML 读取为字符串的方法,这就是我被迫将其读取为. 的原因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
于 2011-08-29T18:27:59.887 回答