请求和响应头
POST的数据
最近项目使用HttpWebRequest请求网页,处理HttpWebResponse返回消息体,发现网页可能是有GZIP压缩等,所得数据乱码,所以相处了解决方案,大家共同学习。
这里是GET方式,POST方式的响应数据基本一样处理即可。
代码:
1 /// <summary> 2 /// 获取请求信息(get方式) 3 /// </summary> 4 /// <param name="strUrl">请求的地址</param> 5 /// <returns>请求的结果</returns> 6 public static string HttpRequestByGet(string strUrl) 7 { 8 string html = ""; 9 //拼写请求主体地址 10 string RequestString = strUrl; 11 12 //生成请求对象 13 HttpWebRequest httprequestPost = (HttpWebRequest)WebRequest.Create(RequestString); 14 15 //设置请求对象属性 16 httprequestPost.Method = "get"; 17 httprequestPost.ContentType = "application/Text/xml"; 18 ////生成响应对象 19 HttpWebResponse res = (HttpWebResponse)httprequestPost.GetResponse(); 20 ////读取返回数据流(编码格式UFT8) 21 Stream responseStream = null; 22 if ("gzip".Equals(res.ContentEncoding)) 23 { 24 responseStream = new System.IO.Compression.GZipStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); 25 } 26 else if ("deflate".Equals(res.ContentEncoding)) 27 { 28 responseStream = new System.IO.Compression.DeflateStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); 29 } 30 else 31 { 32 responseStream = res.GetResponseStream(); 33 } 34 if (responseStream != null) 35 { 36 StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(res.CharacterSet)); 37 html = streamReader.ReadToEnd().Trim(); 38 } 39 //返回结果 40 return html; 41 }
时间: 2024-10-07 10:27:13