代码之家  ›  专栏  ›  技术社区  ›  blez

WebRequest错误?

  •  2
  • blez  · 技术社区  · 16 年前

    编辑:解决了,问题是服务器端的。

    我使用的是C和.NET2,我想知道这是不是一个WebRequest bug。。我用这个方法做了几个很好的请求,一切都很好,但在那之后,每次我都会得到“操作已超时”。我真不明白这是为什么。

    public string RequestPage(string url) {
            HttpWebRequest req = null;
            string line = "";
            string site = "";
    
            try {
                req = (HttpWebRequest) WebRequest.Create(url.Trim());
                req.Timeout = 10000;
    
                StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
                while ((line = reader.ReadLine()) != null) {
                    site += line;
                }
    
                return site;
            } catch (Exception ex) {
                MessageBox.Show("ERROR " + ex.Message);
            }
    
            return null;
        }
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   dtb    16 年前

    我不知道这是否解决了您的问题,但在完成以下操作时,您应该始终处理HttpWebResponse(以及实现IDisposable的其他对象):

    public string RequestPage(string url)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Timeout = 10000;
    
        using (WebResponse resp = req.GetResponse())
        using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
    

    如果您实际上不需要HttpWebRequest的所有特性,那么可以使用 WebClient 取而代之的是:

    public string RequestPage(string url)
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(url);
        }
    }
    
        2
  •  2
  •   Jon Skeet    16 年前

    using (WebResponse response = req.GetResponse())
    using (StreamReader reader = new StreamReader(response.GetResponseStream())
    {
        while ((line = reader.ReadLine()) != null) {
            site += line;
        }
    }
    

    • 这可能是一个非常缓慢的方法来建立一个字符串。使用 StringBuilder
    • 是否确实要删除所有换行符?如果没有,就用 reader.ReadToEnd()