private static string DownloadFile(string fetchUrl, int requestTimeout, int requestRetryCount) { while (true) { try { using (HttpWebResponse response = (HttpWebResponse)CreateWebRequest(fetchUrl, requestTimeout).GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } catch { if (requestRetryCount <= 0) { throw; } requestRetryCount--; } } }
private static WebRequest CreateWebRequest(string fetchUrl, int requestTimeout) { HttpWebRequest.DefaultCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default); WebRequest request = WebRequest.Create(new Uri(fetchUrl)); request.Timeout = requestTimeout; request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; request.Credentials = CredentialCache.DefaultCredentials; request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); request.Proxy = new WebProxy("sinproxy.southpacific.corp.microsoft.com"); return request; }
注意:
若是报错“Unable to connect to the remote server” 而通过浏览器是可以访问到了,那么你肯定是少掉了这句话,如下,是设置代理的。
request.Proxy = new WebProxy("sinproxy.southpacific.corp.microsoft.com");
通过浏览器和自己代码两种方式的访问URL,要保持环境是一样的。