我想从远程服务器读取xml文件,但不知何故服务器没有响应我的请求。因此,Gzip抛出“GZip标头中的幻数不正确”异常。任何的想法?
private static string GetFile()
{
Uri uri = new Uri(@"http://www.iddaa.com.tr/XML/IDDAAMACPROGRAMI/index.htm?iddaadrawid=12.09.2012&iddaadrawide=13.09.2012&foraccess=KSsec654");
string xmlFile;
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(uri);
req.UserAgent =
"MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Encoding", "gzip,deflate");
using (GZipStream zip = new GZipStream(req.GetResponse().GetResponseStream(),
CompressionMode.Decompress))
{
var reader = new StreamReader(zip);
xmlFile = reader.ReadToEnd();
}
return xmlFile;
}
答案 0 :(得分:5)
您不需要使用gzip。如果服务器将gzip标头发送到响应,HttpWebRequest
将自动为您执行此操作。
但您甚至可以使用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();
}
}