myPostResponse =(HttpWebResponse)myPostRequest.GetResponse();
System.IO.Stream stream = myPostResponse.GetResponseStream(); //这里得到返回请求的stream因为要对这个stream执行编码识别和后来的保存数据的操作,
//下面开始自动识别编码
byte[] buf = new byte[1024] ;
......省略部分while( (length=stream.Read(buf,0,buf.Length)) != 0) { //读取stream分析编码
获取到编码后后面需要 sr = new System.IO.StreamReader(stream, this._encoding);
按得到的编码保存数据
但这个stream不支持查找操作,stream.Position不能移回0,请问分析完编码后如何才能保存这个stream到文件?
System.IO.Stream stream = myPostResponse.GetResponseStream(); //这里得到返回请求的stream因为要对这个stream执行编码识别和后来的保存数据的操作,
//下面开始自动识别编码
byte[] buf = new byte[1024] ;
......省略部分while( (length=stream.Read(buf,0,buf.Length)) != 0) { //读取stream分析编码
获取到编码后后面需要 sr = new System.IO.StreamReader(stream, this._encoding);
按得到的编码保存数据
但这个stream不支持查找操作,stream.Position不能移回0,请问分析完编码后如何才能保存这个stream到文件?
System.Exception Message显示:此流不支持查找操作。
System.IO.BufferedStream bs = new System.IO.BufferedStream(stream);
System.IO.BufferedStream bs = new System.IO.BufferedStream(stream);
这样得到的bs的CanSeek属性还是false,bs也无法进行Seek操作
HttpWebResponse.CharacterSet——获取响应的字符集。
HttpWebResponse.ContentEncoding——获取用于对响应体进行编码的方法。这两个方法获取编码,这样就可以直接用你的办法了。
sr = new System.IO.StreamReader(stream, this._encoding);
那就在读取的时候 直接把值保存到某个变量 等待之后使用吧
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); Console.WriteLine("The encoding method used is: " + myHttpWebResponse.ContentEncoding);
Console.WriteLine("The character set used is :" + myHttpWebResponse.CharacterSet);
Encoding encoding = Encoding.GetEncoding( myHttpWebResponse.ContentEncoding );
StreamReader reader= new System.IO.StreamReader(stream, encoding);
zhoufoxcn 提供的方法可以借鉴,但ContentEncoding和CharacterSet判断出来的编码不可靠,各个服务器不一定返回获返回正确的
webrq.Method = "GET";
webrq.AutomaticDecompression = DecompressionMethods.GZip;
webrq.Timeout = 50000;
HttpWebResponse webrp = (HttpWebResponse)webrq.GetResponse();
StreamReader reader = new StreamReader(webrp.GetResponseStream());//不指定编码类型
string html = reader.ReadToEnd();之前我老是喜欢画蛇添足 如:StreamReader reader = new StreamReader(webrp.GetResponseStream(),编码类型);其实不用指定编码类型,系统会自动用使用正确的编码类型;
反正我试了 10多个url
都ok具体原理不晓得是StreamReader能自动匹配编码,还是能自动读取页面流中的charset环境 vs2008 framework 3.5