您不需要使用 gzip。HttpWebRequest
如果服务器将 gzip 标头发送到响应,它将自动为您执行此操作。
但是您甚至可以使用WebClient进一步简化您的代码:
private static string GetFile()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip,deflate";
var xmlFile = client.DownloadString("http://www.iddaa.com.tr/XML/IDDAAMACPROGRAMI/index.htm?iddaadrawid=12.09.2012&iddaadrawide=13.09.2012&foraccess=KSsec654");
return xmlFile;
}
}
或 .NET 4.5 中引入的新HttpClient类:
private async Task<string> GetFile()
{
using (var client = new HttpClient() { BaseAddress = new Uri("http://www.iddaa.com.tr") })
{
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MOZILLA", "5.0"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("(WINDOWS NT 6.1; WOW64)"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("APPLEWEBKIT", "537.1"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("(KHTML, LIKE GECKO)"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("CHROME", "21.0.1180.75"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("SAFARI", "537.1"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
var result = await client.GetAsync("/XML/IDDAAMACPROGRAMI/index.htm?iddaadrawid=12.09.2012&iddaadrawide=13.09.2012&foraccess=KSsec654");
result.EnsureSuccessStatusCode();
return await result.Content.ReadAsStringAsync();
}
}