2017-04-09 99 views
0

嘗試創建兩次獲取請求。但是第二個請求總是拋出WebException消息:「底層連接已關閉:連接意外關閉。」.Net HttpWebRequest獲取請求返回WebException

下面是代碼尖晶石,我用

public string Get(string url) 
    { 
     string strResult = ""; 
     try 
     { 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.Method = "GET"; 
      request.CookieContainer = new CookieContainer(); 
      request.UserAgent = this.UserAgent; 
      request.KeepAlive = false; 

      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      Stream stream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(stream, Encoding.UTF8); 
      strResult = reader.ReadToEnd(); 
      response.Close(); 
     } 
     catch (Exception ex) 
     { 
      //Todo 
     } 
     return strResult; 
    } 

,我要求這url

如果我開始拉琴似乎第二個請求正常的結果。 如果我使用HttpClient類,它似乎也適用。

+0

[求助!運行Fiddler修復我的應用程序???](http://www.telerik.com/blogs/help!-running-fiddler-fixes-my-app-)這篇文章解釋很多,以及[使用HttpClient SSL /基於TLS的客戶端認證](https://pfelix.wordpress.com/2012/12/16/using-httpclient-with-ssltls/) – Fish

+0

change request.KeepAlive = true;解決了我的問題 – Fish

回答

0

當你開始小提琴手的時候,請求之間是否存在任何延遲(你是否在中間點擊了一個斷點)。也許在你的通話之間增加一個快速的Thread.Sleep(250);

另一個要點是,添加一些使用語句來關閉一次性類。

try { 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    request.Method = "GET"; 
    request.CookieContainer = new CookieContainer(); 
    request.UserAgent = this.UserAgent; 
    request.KeepAlive = false; 

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    using (Stream stream = response.GetResponseStream()) 
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { 
     strResult = reader.ReadToEnd(); 
     response.Close(); 
} 
+0

已經嘗試過你的代碼仍然在第二個請求上拋出異常。但是,如果我要求谷歌(www.google.com)終點工作正常。 – Fish

相關問題