前段时间做RSS阅读器,在获取某些博客时出现了编码问题,比如网易博客。
网易博客的RSS,通过跟踪调试发现其编码 CharacterSet = "ISO-8859-1" 因此利用传统的简单转换方式,无法将其转换为默认编码(UTF-8或GB2312/GBK),在多次试验以后发现利用下面的方法可以转换其编码格式:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1
private void TestDecodeISO88591(string RssUrl)
2![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
3
string sResult = "";
4
System.IO.Stream ResponseStream =null;
5
HttpWebResponse hwrp = null;
6
System.IO.StreamReader oStreamReader =null;
7
Encoding UrlEncoding;
8
System.Net.HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(RssUrl);
9
hwr.Method = "GET";
10
hwrp = (HttpWebResponse)hwr.GetResponse();
11
UrlEncoding = Encoding.GetEncoding(hwrp.CharacterSet);
12
ResponseStream = hwrp.GetResponseStream();
13
oStreamReader = new System.IO.StreamReader(ResponseStream, UrlEncoding);
14
sResult = oStreamReader.ReadToEnd();
15
if(hwrp.CharacterSet == "ISO-8859-1") //如果编码为ISO-8859-1才转换
16![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
17
sResult = ConvertISO88591ToEncoding(sResult, Encoding.Default);
18
}
19
hwrp.Close();
20
//处理RSS返回的数据
21
//![](https://www.cnblogs.com/Images/dot.gif)
.
22
}
23![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
24
//转换
25
private static string ConvertISO88591ToEncoding(string srcString, Encoding dstEncode)
26![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
27
String sResult;
28
Encoding ISO88591Encoding = Encoding.GetEncoding("ISO-8859-1");
29
Encoding GB2312Encoding = Encoding.GetEncoding("GB2312"); //这个地方很特殊,必须利用GB2312编码
30
byte[] srcBytes = ISO88591Encoding.GetBytes(srcString);
31
//将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤)
32
byte[] dstBytes = Encoding.Convert(GB2312Encoding, dstEncode, srcBytes);
33
char[] dstChars = new char[dstEncode.GetCharCount(dstBytes, 0, dstBytes.Length)];
34
dstEncode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符
35
sResult = new string(dstChars);
36
return sResult;
37
}
38![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)