无法从传输连接读取数据:控制台应用程序中的连接已关闭错误

时间:2012-07-04 06:33:24

标签: c# httpwebrequest console-application streamreader

我在控制台应用程序中有这个代码,它在循环中运行

 try
 {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);
      request.Headers.Add("Accept-Language", "de-DE");
      request.Method = "GET";
      request.Accept = "text/html";
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
      {
           using (StreamReader reader = new StreamReader(response.GetResponseStream(),
                    Encoding.ASCII))
           {
                string html = reader.ReadToEnd();
                    FindForMatch(html, url);
           }
      }
 }
 catch (Exception ex)
 {
      throw new Exception(ex.Message);
 }

经过几次循环后

  

无法从传输连接中读取数据:连接已关闭

错误。知道为什么会这样吗?感谢名单..

3 个答案:

答案 0 :(得分:23)

添加

request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10; 

它工作得很好..

我发现它来自这篇博文

WebRequest and Unable to read data from the transport connection Error

答案 1 :(得分:0)

我刚尝试了代码,循环了10次以加载google.com,它对我有用。 search有什么特别之处 - 也许尝试用另一个uri替换它。我没有包含findForMatch - 我认为它没有做任何导致异常的事情。

答案 2 :(得分:-5)

尝试将阅读器放在try catch

的finally块中