2014-04-13 82 views
0

對我的代碼有任何建議。我不知道爲什麼表現不佳。 我的代碼大約需要200毫秒,而瀏覽器僅有50毫秒,如下圖:HttpWebRequest(200ms)比瀏覽器(50ms)慢4倍

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url)); 
request.Proxy = null; 
request.Method = "GET"; 
request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*"; 
request.Headers.Add("Accept-Language", "zh-CN"); 
request.UserAgent = "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"; 

request.Headers.Add("Accept-Encoding", "gzip, deflate"); 
request.KeepAlive = true; 
request.AllowAutoRedirect = false;   
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
string str; 
Stream st = response .GetResponseStream(); 
if (response .ContentEncoding.ToLower().Contains("gzip")) 
{ 
    st = new GZipStream(st, CompressionMode.Decompress); 
} 
StreamReader reader = new StreamReader(st); 
str = reader.ReadToEnd(); 
reader.Close(); 
response.Close(); 
+2

你確定你的瀏覽器沒有緩存數據嗎? –

+0

來比較兩件事情,它可能是用來顯示它們兩個。 – GameAlchemist

+0

我使用Http分析器v7來獲取數據。在訪問目標網站之前清除瀏覽器緩存。 – user2724902

回答

0

你爲什麼手工處理解壓?只需使用

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; 

這也將添加了accept-encoding頭和清除瀏覽器緩存後再次檢查。