HTTP 请求有时我们已经指定了网页的编码可是获取的数据仍然乱码

C# HTTP 请求有时我们已经指定了网页的编码可是获取的数据仍然乱码

原因有可能不是编码的问题,好像是因为返回的数据做了压缩

我们做如下操作

            string htmlString = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//为指定的 URI 方案初始化新的 System.Net.WebRequest 实例
            request.AllowWriteStreamBuffering = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.MaximumResponseHeadersLength = -1;
            request.Accept = "text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,image / apng,*/*;q=0.8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "GET";
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.Headers.Add("Cache-Control", "no-cache");
            request.Host = "www.jsedu.sh.cn";
            request.Headers.Add("Pragma", "no-cache");
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.Headers.Add("Cookie", "security_session_verify=3af9c747bbf42f973a2d903637af7ff2; PASSPORTID=q4v4fgi3hkrndce5h2rstvrih3");
            request.KeepAlive = true;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stm = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);

            StreamReader sr = new StreamReader(stm, Encoding.GetEncoding(encode.ToUpper()));
            string txt = sr.ReadToEnd();
            stm.Close();
            htmlString = txt;
            return htmlString;

你可能感兴趣的:(.net)