我正在尝试从
http://aplweb.soriana.com/foto/fotolib/14/7503003936114/7503003936114-01-01-01.jpg
使用WebClient。
当我以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");
}我已经尝试过.DownloadData()、异步方法、HttpClient、WebRequest直接..我总是犯同样的错误。

有什么想法吗?
发布于 2021-02-06 01:26:30
您的代码很好,但这是一个特定于服务器的行为。添加一些请求头可以解决这个问题。
下面是一个使用HttpClient的示例
class Program
{
private static readonly HttpClient client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
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");
client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");
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);
}
}
}控制台输出
Downloading...
Saving...
OK.下载图像

发布于 2021-02-06 01:47:46
服务器似乎只为支持压缩的请求提供服务。WebClient不支持自动压缩。您可以通过继承您自己的类(如this answer中所述)来启用对压缩的支持。
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}然后使用MyWebClient而不是WebClient。
https://stackoverflow.com/questions/66072583
复制相似问题