我写完这篇文章的人离开公司之后,我继承了一些代码。显然它从未奏效,但我不知道为什么。
它正试图从台湾证券交易所网站下载包含外汇汇率的CSV文件。
网址为
如果我将该网址直接粘贴到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;
}
任何帮助将不胜感激
答案 0 :(得分: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;
这应该有用。