c#访问http接口的编码问题

时间:2022-02-01 04:15:49

  记一次访问http数据接口的爬坑经历,一般访问一个http接口。

无非就是这么几行代码:

  

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url"); HttpWebResponse response = (HttpWebResponse)request.GetResponse();    System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));//设置响应编码,乱码的话 Console.Write(sr.ReadToEnd()); sr.Close(); response.Close();

可是这次,死话乱码。PostMan下正常的。。在浏览器中直接访问,设置编码为utf-8b也是可以正常显示的。。用c#后台代码测试了各种编码都以无效,,告终。。

查看响应头:

Content-Encoding gzip。。。。刚开始被我略过了。。后来搜乱码google到了博客园的博问。

更新代码如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //先把响应流以gzip形式解码,然后再读取。结果success....... Stream stm = new GZipStream(response.GetResponseStream(),CompressionMode.Decompress);        System.IO.StreamReader sr = new StreamReader(stm, System.Text.Encoding.GetEncoding("utf-8")); Console.Write(sr.ReadToEnd()); sr.Close(); response.Close();