【问题标题】:Char Array of Byte Array of HttpWebResponse of HttpWebRequest returns "System.Net.HttpWebRequest"HttpWebRequest 的 HttpWebResponse 的 Byte Array 的 Char Array 返回“System.Net.HttpWebRequest”
【发布时间】:2010-12-05 21:37:09
【问题描述】:

我正在尝试使用 WebRequest.GetResponse(); 请求网页并将该响应转换为字符数组,这样我就可以对数组进行排序并获取页面上的任何 HREF 标记。问题是,在我的代码中的某个地方,响应变成了“System.Net.HttpWebRequest”,而不是应该从页面中检索的 HTML。

获取char数组的代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlTextBox.Text);
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            bytearray = encoding.GetBytes(Convert.ToString(response));
            chararray = encoding.GetChars(bytearray);

搜索链接的代码(为故障排除注释):

for (int i = 0; i < chararray.Length; i++)
{
    // Get all HREFs
    if (i < 500 & chararray[i] == 'h' & chararray[i + 1] == 'r' & chararray[i + 2] == 'e' & chararray[i + 3] == '=' & chararray[i + 4] == '"')
    {
        for (int tempi = 0; bytearray[i + 4 + tempi] != '"';)
        {
             tempstring = tempstring + chararray[i + 4 + tempi].ToString();
        }
        urlarray[urlarray.Length + 1] = tempstring;
        i = i + 4;
    }
}
scrapeLink1.Text = urlarray[1];

如果我遗漏了什么,或者需要更多信息,请告诉我。

【问题讨论】:

    标签: arrays httpwebrequest httpwebresponse


    【解决方案1】:

    响应是您必须首先读取的

    HttpWebRequest request = WebRequest.Create(urlTextBox.Text) as HttpWebRequest;
    if (request != null)
    {        
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7";
        using (HttpWebRepsonse response = request.GetResponse() as HttpWebResponse)
        using (StreamReader rdr = new StreamReader(response.GetResponseStream())
        {
            string result = rdr.ReadToEnd();
        }
    }
    

    【讨论】:

    • 你能说得更具体一点吗?例如,我将如何从响应中读取流?我是否需要将响应声明为 webrequest 以外的内容?
    • 乔尔已经给出了代码。但是,如果我是你,我只会使用 WebClient 类。使用适合您的 DownloadData() 重载。
    • @feroze webclient 无法轻松设置他似乎需要的 UserAgent。
    • 谢谢,代码有效。我问这个例子的原因是因为当我问的时候它不在答案中。
    猜你喜欢
    • 2018-01-22
    • 2019-04-04
    • 2015-04-03
    • 2012-06-03
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多