Unable to read data from the transport connection:

2019-02-12 12:16发布

I have this code in console application and it runs in a loop

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

after few loops it gives

Unable to read data from the transport connection: The connection was closed

error. any idea why this happen? thanx..

3条回答
别忘想泡老子
2楼-- · 2019-02-12 12:23

I just tried the code, looping 10 times to load google.com and it worked for me. Is there something special about search - perhaps try replacing it with another uri. I did not include findForMatch - I assume it is not doing anything that would cause the exception.

查看更多
再贱就再见
3楼-- · 2019-02-12 12:26

After adding

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

it works fine..

I found it form this blog post

WebRequest and Unable to read data from the transport connection Error

查看更多
爷的心禁止访问
4楼-- · 2019-02-12 12:34

Try disposing the reader in the finally block of your try catch

查看更多
登录 后发表回答