为什么httpwebrequest C#返回非压缩响应

时间:2016-03-08 14:14:14

标签: c#

我正在为我的某个网站构建一个自动登录应用程序。我在C#中开发了自动登录工具。我已经使用httpwebrequest在登录页面上进行帖子调用。我正面临网页压缩的问题。在某些计算机中,我没有得到压缩响应,而在其他计算机中,我得到了响应。任何人都可以建议我如何保证得到压缩响应。以下是我为httpwebrequest编写的代码:

httpRequest.Connection = "keepalive";
httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequest.UserAgent = "Mozilla/5.0 (Windows T 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36";
httpRequest.UnsafeAuthenticatedConnectionSharing = true;            
httpRequest.Headers.Set("Cache-Control", "no-cache"); 
httpRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(postdata);
httpRequest.ContentLength = bytes.Length;
requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
response = (HttpWebResponse)httpRequest.GetResponse();
HttpWebResponse response2 = response;  
switch (response2.StatusCode)
{
    case HttpStatusCode.OK:      
         responseStream = response2.GetResponseStream();                        
         if (response2.ContentEncoding.ToLower().Contains("gzip"))
         {
            str = new StreamReader(new GZipStream(responseStream, CompressionMode.Decompress), Encoding.UTF8).ReadToEnd();
         }
         else if (response2.ContentEncoding.ToLower().Contains("deflate"))
         {
             str = new StreamReader(new DeflateStream(responseStream, CompressionMode.Decompress), Encoding.UTF8).ReadToEnd();
         }
         else
         {
              str = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
          }              
          responseStream.Close();
          responseStream = null;
    break;
 }

0 个答案:

没有答案