2014-02-25 53 views
1

在編寫它的人離開公司後,我繼承了一些代碼。顯然它從來沒有工作,但我不知道爲什麼。httpwebrequest超時錯誤c#

它試圖從臺灣證券交易所網站下載包含外匯匯率的CSV文件。

的網址是

http://rate.bot.com.tw/Pages/UIP004/Download0042.ashx?lang=en-US&fileType=1&afterOrNot=0&whom=SGD&date1=20110401&date2=20110430

如果我粘貼URL直接到Internet Explorer,我得到迴應馬上問我,如果我想打開或保存文件,我可以打開和保存該文件沒有問題。

當我運行C#代碼來獲取文件時,大約90秒後出現錯誤消息「操作已超時」。我試圖將超時時間改爲3分鐘,以防需要更長的時間,但仍然沒有運氣。我可以看到本地創建的空文件,但沒有任何內容填充到它。

private static void GetVendorFiles(String sUrl, String sFileNameToWrite, String sProxy) 
{ 
    DateTime dtStart = System.DateTime.Now; 

    using (CertWebClient client = new CertWebClient()) 

    try 
    { 
     WebProxy proxy = new WebProxy(sProxy); 
     proxy.Credentials = CredentialCache.DefaultCredentials; 
     WebRequest.DefaultWebProxy = proxy; 

     //Override the default policy of System.Net not accepting self-signed certificates 
     System.Net.ServicePointManager.ServerCertificateValidationCallback 
     = CertificatePolicy.ValidateSSLCertificate; 

     //Download file and write to network drive 
     client.DownloadFile(sUrl, sFileNameToWrite); 

     proxy = null; 

    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
     TraceHelper.WriteLine("PathHelper.DownLoadFiles:" + ex.Message); 
     throw; 
    } 
} 

我嘗試了兩種不同的ContentType值 - 「text/plain」和「application/octet-stream」。沒有任何區別。

class CertWebClient : WebClient  
{ 
    protected override WebRequest GetWebRequest(Uri address) 
    { 

     try 
     { 
      HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); 
      request.ContentType = "application/octet-stream"; 
      return request; 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      TraceHelper.WriteLine("Taiwan FX Rates Web Certificate Error:" + ex.Message); 
      throw; 
     } 
    } 

    public static void Getcert(string certLocation,string sPassword) 
    { 

     if (certLocation == "") 
     { 
      throw new ArgumentException ("Null certificate location passed to CertWebClient"); 
     } 

     if (sPassword == "") 
     { 
      throw new ArgumentException("Null password passed to CertWebClient"); 
     } 
     certificateLocation = certLocation; 
     certPassword = sPassword; 
    } 

    private static string certificateLocation; 
    private static string certPassword; 
} 

任何幫助,將不勝感激

回答

1

設置以下屬性:

request.Method = "GET"; 
request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36" 
request.KeepAlive = true; 
request.Timeout = Timeout.Infinite; 

這應該工作。

+0

這工作的一種享受。非常感謝。 –