简体   繁体   中英

C# Code to download an image from a “not so easy” CDN

Im trying to download an image from a specific website.
Actually, my code is up and running in production for months, but it's not able to download imagens from this specific website

The image URL I need to download is this one: (for instance) http://static7.kabum.com.br/produtos/fotos/64297/64297_index_g.jpg

The codes I tried so far:

Method 1 -> (failed)

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);
    }
}

Method 2 -> (also failed)

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

Both methods fail with the following exception

“Parameter not valid” exception loading System.Drawing.Image

StackTrace = " em System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) in System.Drawing.Image.FromStream(Stream stream) in MonitorLib.Helper.RequestPageHelper.RequestDowloadPage(Boolean proxy, Strin...

I guess the image data is incomplete or compacted, but the URL Works fine on any browser

any thoughts? thanks a lot friends

you could use the WebClient.DownloadFile() method.

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);
}

This seems to be problem with the server responding with bad header that the browsers are able to ignore and get past. You need to tell your application to do the same. There are several options for doing that. The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF, In WinForms? should be able to guide you to the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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