【问题标题】:Unable to read data from the transport connection: The connection was closed error in console application无法从传输连接读取数据:控制台应用程序中的连接已关闭错误
【发布时间】:2012-07-04 15:11:26
【问题描述】:

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

 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);
 }

几个循环后它给出了

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

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

【问题讨论】:

  • 可以是任何东西。也许服务器不喜欢你锤它。
  • 顺便说一句,不要重新抛出你的异常,最好记录你的异常或让异常冒泡到更高的位置,然后在那里捕获它
  • 异常来自`reader.ReadToEnd()'

标签: c# httpwebrequest console-application streamreader


【解决方案1】:

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

【讨论】:

  • 它不会一直发生。异常来自`reader.ReadToEnd()'
【解决方案2】:

尝试将阅读器放置在 try catch 的 finally 块中

【讨论】:

    【解决方案3】:

    添加后

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

    效果很好..

    我在这篇博文中找到了它

    WebRequest and Unable to read data from the transport connection Error

    【讨论】:

    • 嗯,我不知道为什么会这样,但确实如此!诡异的!也许是 IIS Express 什么的。
    • 非常感谢,它对我的​​情况有效,我挣扎了一段时间。
    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2011-04-23
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多