[英]character encoding from XML to Java
<?xml version="1.0" encoding="UTF-8"?>
我只介紹一些我認為有意義的代碼。
我正在通過http請求從一個xml中讀取一些信息,如下所示:
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
如果我將字符串xml打印到屏幕上,我已經可以看到編碼問題
然后返回文件我有這個
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
盡管我從http請求中正確獲取了信息,但是在顯示數據時我在字符編碼方面遇到了問題。
我已經嘗試過進行is.setEncoding(“ UTF-8”)了,但是沒有用。
問題是您將xml轉換為字符串(字符),請不要這樣做(您很可能使用了錯誤的編碼並損壞了xml)。 將xml視為二進制數據(字節) 。
您可以使用EntityUtils.toByteArray
(可以),也可以將HttpEntity流直接傳遞到xml解析器(理想)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.