簡體   English   中英

使用WebClient下載文件時出現異常(C#)

[英]Exception when downloading file using webclient (c#)

我正在使用ac#代碼從網站下載文件。 我正在使用webclient類:

using (var client = new WebClient())
{                    
    client.DownloadFile(
        @"http://www.cftc.gov/files/dea/history/com_disagg_txt_2018.zip",
        @"destination"
     );
}

該代碼可以正常工作幾個星期。 但是大約一周前它停止工作了。 每當我運行代碼時,它都會引發異常:

遠程主機已關閉現有連接。 (錯誤代碼10054)

我在想,也許網站開始只允許通過瀏覽器下載,所以我補充道:

client.Headers["User-Agent"] ="Mozilla/5.0 (Windows NT 6.3; rv:36.0) 
Gecko/20100101 Firefox/36.0";

但是,它沒有解決問題。

有人知道解決方案嗎?

這種失敗很常見。
該站點已實施TLS 1.2協議。

即使您在URI中指定了Http: ,協議也會切換為Https:

您只需啟用它即可,因為.Net ServicePointManager (仍然)默認為Ssl3/Tls 1.0

使用以下代碼對其進行測試:

string Url ="http://www.cftc.gov/files/dea/history/com_disagg_txt_2018.zip";

Uri URI = new Uri(Url, UriKind.Absolute);
WebClient_DownLoad(URI, FileName);


public void WebClient_DownLoad(Uri URI, string FileName)
{
    using (WebClient webclient = new WebClient())
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        webclient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
        webclient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
        webclient.Headers.Add(HttpRequestHeader.Accept, "ext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
        webclient.Headers.Add(HttpRequestHeader.KeepAlive, "keep-alive");
        webclient.UseDefaultCredentials = true;

        webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(WebClient_DownloadComplete);
        webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WebClient_DownloadProgress);

        webclient.DownloadFileAsync(URI, FileName);
    };
}

private void WebClient_DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
    string Result = string.Format("Received: {0}  Total: {1}  Percentage: {2}", 
                         e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
    //Update the UI
    Console.WriteLine(Result);
}

private static void WebClient_DownloadComplete(object sender, AsyncCompletedEventArgs e)
{
    if (!e.Cancelled)
    {
        if (e.Error != null)
            // Update the UI: transfer completed.
            Console.WriteLine("Error: " + e.Error.Message);

    }else{
        // Update the UI: transfer Cancelled.
        Console.WriteLine("Cancelled");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM