我正在使用WebClient
,并且正在尝试下载以下CSS文件:https://assets.staples-static.com/NC1/pn/bui/20181010140727/styleguide/docs/css/atcOverlay.css
这是我尝试使用的代码:
WebClient webClient = new WebClient();
string css = webClient.DownloadString("https://assets.staples-static.com/NC1/pn/bui/20181010140727/styleguide/docs/css/atcOverlay.css");
它没有用-我有一个超时异常。
然后我尝试添加与浏览器相同的标题:
WebClient webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
webClient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
webClient.Headers.Add("Upgrade-Insecure-Requests", "1");
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
webClient.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
webClient.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
webClient.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
string css = webClient.DownloadString("https://assets.staples-static.com/NC1/pn/bui/20181010140727/styleguide/docs/css/atcOverlay.css");
相同的结果。
我什至尝试将webClient.DownloadString
替换为webClient.DownloadData
,甚至完全替换为HttpWebRequest
。所有人都给了我相同的结果。
使用 Fiddler (我看到 Raw 标签)时看到的唯一区别是Connection
标头({{1} }和浏览器中的Keep-Alive
以及页眉的顺序(我试图尽可能地匹配它们,但我只是找不到一种方法来放置keep-alive
和HOST
首先在CONNECTION
之下。
我尝试从同一主机下载其他CSS文件,而从其他主机下载就很好。
有人遇到这样的问题吗?我有什么想念的吗?我还能尝试什么?
我从下面的评论中尝试了Poul Bak的建议。没用这是我使用的代码:
GET
答案 0 :(得分:1)
我做了一些测试,找到了使其工作的方法。问题是'Connection'
标头值未设置为'Keep-Alive
'。
设置使其生效:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
httpClient.DefaultRequestHeaders.Add("Host", "assets.staples-static.com");
httpClient.DefaultRequestHeaders.Add("Pragma", "no-cache");
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
httpClient.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.9");
var result = await httpClient.GetAsync("https://assets.staples-static.com/NC1/pn/bui/20181010140727/styleguide/docs/css/atcOverlay.css");
string text = await result.Content.ReadAsStringAsync();
现在我得到大约10kb的字符串。