亂碼問題總算解決了。
下面這段代碼用來獲取文章內容,并通過NekoHTML來解析獲得去掉HTML標簽的文章內容.標紅的地方就是用來設置字符集的,第一個是XML格式的字符集(似乎沒什么用),第二個地方是將字符串的內容通過輸入流讀入,如果不指定的話在GAE中默認的是ISO-8859-1(本地的話以設置的文件的字符類型為主),第三個地方是設置XML解析器的字符集。昨晚就是第二個地方沒有設置,導致亂碼。在測試的過程中還學到一點:GBK->ISO-8859-1 的過程是不可逆的,也就是說如果把中文字符轉成了ISO-8859-1的話,就再也轉不過來了,中文變成了"????"。因此在保險起見,輸入輸出流在使用的時候最好都加上字符集。
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 }
今天受到了不少關注,非常高興,非常感謝支持我的同學們,我會慢慢的將開發的過程寫出來與大家分享。亂碼問題總算解決了。
posted @
2009-11-04 01:29 漁人 閱讀(582) |
評論 (0) |
編輯 收藏