我的程序不会从网站(C#)加载图片

时间:2018-07-18 06:23:28

标签: c# timeout httpwebrequest

今天,在使用我几年前编写的程序时,我遇到了这样一种情况,即从网站上加载缩略图最终导致超时而不是加载。我的Web浏览器能够很好地打开文件,并且在进行了数小时的故障排除之后,我没有任何想法。

public static Image GetThumbNail(OnlineImageInfo info)
    {
        //Check if thumbnail has been cached to disk
        FileInfo file = new FileInfo(string.Format("{0}{1}", Config.ActiveConfig.ThumbnailCachePath.FullName,
            info.PreveiwFileName));
        if (!file.Exists)
        {
            //Generate a web request
            HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(info.PreveiwURL);
            request.Method = "GET";

            request.UserAgent = ".NET Framework Test Client";
            request.Timeout = 10000; //I added the timeout to stop the program from hanging while trying to load this thumbnail
            WebResponse response = null;
            try
            {
                response = request.GetResponse();
                //cache the image to disk
                using (var fs = file.Create())
                {
                    using (var strm = response.GetResponseStream())
                    {
                        strm.CopyTo(fs);
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            catch (WebException e)
            {
                //timed out
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (response != null)
                    response.Dispose();
            }


        }
        //Load image from disk to RAM
        Image result = null;
        MemoryStream mem = new MemoryStream();
        using (var fs = TryGetFileStream(file))
        {
            fs.CopyTo(mem);
            result = Image.FromStream(mem);
        }


        return result;
    }

奇怪的是,我从该网站上加载了成千上万个缩略图,但我从未发生过这种情况。谁能想到为什么该文件在我的程序上而不是在浏览器上超时,或者我如何进一步对其进行故障排除?

编辑: 在尝试了以下注释中的建议无济于事之后,我尝试将请求强制为Http而不是Https,然后低下看该请求突然生效。我想弄清楚为什么会出现这种行为,但至少现在可以正常工作。

HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(info.PreveiwURL.Replace("https:","http:"));
            request.Method = "GET";
            request.Referer = info.SourceWebsite;
            request.UserAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0";
            request.Timeout = 5000;
            WebResponse response = null;

0 个答案:

没有答案