使用 C# 从 url 下载 .webp 图像

Fra*_*aga 1 c# webclient download webp

我正在尝试从以下位置下载图像

http://aplweb.soriana.com/foto/fotolib/14/7503003936114/7503003936114-01-01-01.jpg

使用网络客户端。

当我在 Chrome 中浏览图像时,图像就在那里: 在此输入图像描述

url 以 .jpg 结尾,但图像为 .WEBP 格式。

    using (WebClient wb = new WebClient())
    {                  
         wb.DownloadFile("http://aplweb.soriana.com/foto/fotolib//14/7503003936114/7503003936114-01-01-01.jpg", "image.jpg");
    }
Run Code Online (Sandbox Code Playgroud)

我直接尝试过.DownloadData()、asyng方法、HttpClient、WebRequest。..我总是遇到同样的错误。

在此输入图像描述

任何想法?

aep*_*pot 5

您的代码很好,但这是特定于服务器的行为。添加一些请求标头可以解决该问题。

这是一个使用的示例HttpClient

class Program
{
    private static readonly HttpClient client = new HttpClient(new HttpClientHandler()
    {
        AutomaticDecompression = DecompressionMethods.All // automatically adds HTTP header "Accept-Encoding: gzip, deflate, br"
    });

    static async Task Main(string[] args)
    {
        client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        try
        {
            Console.WriteLine("Downloading...");
            byte[] data = await client.GetByteArrayAsync("http://aplweb.soriana.com/foto/fotolib//14/7503003936114/7503003936114-01-01-01.jpg");
            Console.WriteLine("Saving...");
            File.WriteAllBytes("image.jpg", data);
            Console.WriteLine("OK.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台输出

Downloading...
Saving...
OK.
Run Code Online (Sandbox Code Playgroud)

下载的图片

在此输入图像描述