2011-05-04 161 views
3

我有一個問題,在下載數據時顯示錯誤「The Operation has timed out」。如何解決「操作超時」錯誤

我能做些什麼來解決這個錯誤?我使用Win窗體(C#)這裏是我的代碼,請檢查並提供建議。我應該在哪裏更改代碼,請幫我...

public void ProcessData() 
     { 


      try 
      { 
      string MessageTitle = ""; 
      int pages = Convert.ToInt32(txtPages.Text); 

      for (int k = Count; k <= pages; k++) 
      { 

       string url = "http://www.yellowpages.com/" +StateName.ToLower()+ "/" + CategoryName + "?g=" + StateName + "&page=" + k + "&q=" + CategoryName + "";//txtYP.Text + k; 
       System.Net.HttpWebRequest httpRequest; 
       System.Net.HttpWebResponse httpResponse; 
       System.IO.StreamReader SReader; 
       string html; 
       httpRequest = (System.Net.HttpWebRequest)(System.Net.HttpWebRequest.Create(url)); 
       httpRequest.Method = "GET"; 
       httpResponse = (System.Net.HttpWebResponse)(httpRequest.GetResponse()); 
       SReader = new StreamReader(httpResponse.GetResponseStream()); 
       html = SReader.ReadToEnd(); 
       string strDummy = html; 
       httpResponse.Close(); 

回答

1

請求超時之前多長時間? 你能夠從網頁瀏覽器導航到網址嗎?

將HttpWebRequest上的HttpWebRequest.ReadWriteTimeout屬性設置爲比當前值高得多的值。默認值是5分鐘。 不知道爲什麼它應該需要超過5分鐘。

而是上阻塞的GetResponse的,你還可使用異步回調(BeginGetResponse/EndGetResponse)。

編輯

<system.diagnostics> 
    <trace autoflush="true" /> 
    <sources> 
    <source name="System.Net"> 
     <listeners> 
     <add name="System.Net"/> 
     </listeners> 
    </source> 
    <source name="System.Net.HttpListener"> 
     <listeners> 
     <add name="System.Net"/> 
     </listeners> 
    </source> 
    <source name="System.Net.Sockets"> 
     <listeners> 
     <add name="System.Net"/> 
     </listeners> 
    </source> 
    <source name="System.Net.Cache"> 
     <listeners> 
     <add name="System.Net"/> 
     </listeners> 
    </source> 
    </sources> 
    <sharedListeners> 
    <add 
     name="System.Net" 
     type="System.Diagnostics.TextWriterTraceListener" 
     initializeData="trace.log" 
     traceOutputOptions = "ProcessId, DateTime" 
      /> 
    </sharedListeners> 
    <switches> 
    <add name="System.Net" 
     value="Verbose" /> 
    <add name="System.Net.Sockets" 
     value="Verbose" /> 
    <add name="System.Net.Cache" 
     value="Verbose" /> 
    <add name="System.Net.HttpListener" 
     value="Verbose" /> 
    </switches> 
</system.diagnostics> 

添加此欄目內configuration部分應用程序的app.config中。 添加上述內容後,重新構建解決方案並運行它。 查看您的應用程序的bin目錄中寫入的trace.log以獲取更多詳細信息。

+0

感謝您給予回覆,,,是的,我能夠瀏覽從網絡瀏覽器的網址...如何設置Httprequest時間,請helpme ....在哪裏我可以編寫代碼... – 2011-05-04 08:00:10

+0

爲什麼它顯示此錯誤「請求被中止:連接意外關閉。」 – 2011-05-04 08:08:55

+0

在我看來,你正在錘擊一個你不擁有請求的站點,並且正在被他們的防火牆\ bot機制阻止。 – Arunas 2011-05-04 10:01:43

0

添加到您的代碼:

httpRequest.Timeout = 3600000;

這會將請求超時增加到一個小時。

+0

嗨,謝謝你給予respose ...實際上我們不知道它需要多少時間可能是5小時或7小時..... – 2011-05-04 12:57:43

+0

然後把它放在10個小時,一些程序有近24小時超時他們的要求。所以它的測試很好。 – Arrabi 2011-05-04 13:08:43