简体   繁体   English

HttpClient 图像文件未完全下载 c#

[英]HttpClient Image file is not is not fully downloaded c#

I have this code:我有这个代码:

for(int i = 0; i< Alim(exo).Count; i++)
             {
                APIResource a = new APIResource();
                a = Alim(exo)[i];
              
                object test;
                if (!_cache.TryGetValue(a.name, out test))
                {
                    
                    _cache.Set(a.name, a.name);
                  
                    //System.Threading.Thread.Sleep(2000);
                    using (var httpClient = new HttpClient())
                    {
                        using (var request = new HttpRequestMessage(HttpMethod.Get, Alim(exo)[i].url))
                        {
                            using (
                                Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
                                stream = new FileStream(Path.Combine(specificFolder, Alim(exo)[i].name), FileMode.Create, FileAccess.ReadWrite))
                            {
                                await contentStream.CopyToAsync(stream);
                                
                            }
                        }
                    }

                    MessageBox.Show("coucou");
                    
                }
                exo[i].ThumbnailLocalPath = @"secretpath" + a.name;
             }

But my images are not fully donwloaded look at screenshot:但是我的图片没有完全下载看截图:

在此处输入图像描述 在此处输入图像描述

To make it Work i have to put the thread.sleep.为了使它工作,我必须把thread.sleep.

I also tried with Webclient.DownloadFile我也试过Webclient.DownloadFile

My function is Async.我的 function 是Async.

Thanks you.谢谢。

<html> <head><title>429 Too Many Requests</title></head> <body> <center><h1>429 Too Many Requests</h1></center> <hr><center>openresty</center> </body> </html>

So a 429 is exactly what I was talking about , you're issuing too many requests in too short of a timespan, according to their server's configuration and response.所以 429 正是我所说的,根据他们的服务器的配置和响应,你在太短的时间内发出了太多的请求。

If they're generous, they include a Retry-After response header.如果他们很慷慨,他们会包含一个Retry-After响应 header。 Otherwise you'll have to retry (preferably with an exponential backoff , ie 1.x, 2.x, 4.x, ... seconds where x is a random number of milliseconds) until you succeed.否则,您将不得不重试(最好使用 指数退避,即 1.x, 2.x, 4.x, ... seconds 其中 x 是随机的毫秒数),直到您成功。

In order to do this, you should start by saving and inspecting the response:为此,您应该首先保存并检查响应:

var response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
    // wait, then retry
}

And also, don't dispose HttpClient, reuse it for your application lifetime.而且,不要丢弃 HttpClient,在您的应用程序生命周期中重用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM