C#代码从“;不那么容易”;CDN

本文关键字:CDN 代码 | 更新日期: 2023-09-27 17:58:03

我正在尝试从特定网站下载图像
事实上,我的代码已经在生产中运行了几个月,但它无法从这个特定的网站下载图像

我需要下载的图像URL如下:(例如)http://static7.kabum.com.br/produtos/fotos/64297/64297_index_g.jpg

到目前为止我尝试过的代码:

方法1->(失败)

string url = "http://static7.kabum.com.br/produtos/fotos/64297/64297_index_g.jpg";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = (timeout == 0 ? 30 : timeout) * 1000;
request.KeepAlive = false;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36";
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
    const int BUFFER_SIZE = 16 * 1024;
    var buffer = new byte[BUFFER_SIZE];
    // if the remote file was found, download it
    using (Stream inputStream = response.GetResponseStream())
    using (Stream outputStream = File.Create(fileName, BUFFER_SIZE))
    {
        int bytesRead;
        do
        {
            bytesRead = inputStream.Read(buffer, 0, buffer.Length);
            outputStream.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);
    }
}

方法2->(同样失败)

[..]
using(Image webImage = Image.FromStream(response.GetResponseStream()))
{
    webImage.Save(fileName);
}
[..]

两种方法都失败,出现以下exception

加载System.Drawing.Image 时出现"参数无效"异常

StackTrace="em System.Drawing.Image.FromStream(Stream,布尔使用EmbeddedColorManagement,布尔validateImageData)中的System.Drawing.Image.FromStream(Stream)MonitorLib.Helper.RequestPageHelper.RequestDowloadPage(布尔代理,Strin。。。

我猜图像数据不完整或压缩,但URL在任何浏览器上都能正常工作

有什么想法吗?感谢很多朋友

C#代码从“;不那么容易”;CDN

您可以使用WebClient.DownloadFile()方法。

var fileName = @"C:'path'to'file.jpg";
var url = "http://static7.kabum.com.br/produtos/fotos/64297/64297_index_g.jpg";
using (var client = new WebClient())
{
    client.DownloadFile(url, fileName);
}

这似乎是服务器响应错误标头的问题,浏览器可以忽略并通过该标头。你需要告诉你的应用程序也这样做。有几种选择。服务器违反了协议。Section=ResponseHeader Detail=CR后面必须跟LF,在WinForms中?应该能够引导你走向正确的方向。