亂碼問題總算解決了。
下面這段代碼用來獲取文章內(nèi)容,并通過NekoHTML來解析獲得去掉HTML標(biāo)簽的文章內(nèi)容.標(biāo)紅的地方就是用來設(shè)置字符集的,第一個是XML格式的字符集(似乎沒什么用),第二個地方是將字符串的內(nèi)容通過輸入流讀入,如果不指定的話在GAE中默認(rèn)的是ISO-8859-1(本地的話以設(shè)置的文件的字符類型為主),第三個地方是設(shè)置XML解析器的字符集。昨晚就是第二個地方?jīng)]有設(shè)置,導(dǎo)致亂碼。在測試的過程中還學(xué)到一點:GBK->ISO-8859-1 的過程是不可逆的,也就是說如果把中文字符轉(zhuǎn)成了ISO-8859-1的話,就再也轉(zhuǎn)不過來了,中文變成了"????"。因此在保險起見,輸入輸出流在使用的時候最好都加上字符集。
1 public String getContent(String xwnr) throws Exception {
2 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><content>" + xwnr + "</content>";
3 DOMFragmentParser parser = new DOMFragmentParser();
4 DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
5
6 InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
7
8 InputSource input = new InputSource(is);
9 input.setEncoding("UTF-8");
10 try {
11 parser.parse(input, node);
12 } catch (IOException e) {
13 e.printStackTrace();
14 } catch (SAXException se) {
15 se.printStackTrace();
16 }
17 StringBuffer newContent = new StringBuffer();
18 this.getText(newContent, node);
19
20 /*String str = ( new String(
21 newContent.toString().getBytes("Windows-1252"), "UTF-8" ));*/
22
23 String str = newContent.toString();
24
25 if (str.length()>200){
26 return str.substring(0,200);
27 }else{
28 return str;
29 }
30 }
今天受到了不少關(guān)注,非常高興,非常感謝支持我的同學(xué)們,我會慢慢的將開發(fā)的過程寫出來與大家分享。亂碼問題總算解決了。
posted on 2009-11-04 01:29
漁人 閱讀(582)
評論(0) 編輯 收藏