我正在尝试使用HttpClient获取图像,我收到此错误:
HttpRequestException:发送请求时发生错误
使用WebClient和DownloadData方法,工作正常。
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4");
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.GetAsync("cookieGenerateUrl").Wait();
client.DefaultRequestHeaders.Remove("Accept");
client.DefaultRequestHeaders.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
var imagem = client.GetByteArrayAsync(imageUrl).Result;
HttpClient类上的WebClient.DownloadData相当于什么?
答案 0 :(得分:1)
这里的问题可能是你在调用client.GetByteArrayAsync
时没有正确处理等待的问题。
修复是:
var res = await client.GetByteArrayAsync(url);
或
byte[] arr;
client.GetByteArrayAsync(url).ContinueWith((x) => arr = x.Result);