0

我使用 Wikimedia API Sandbox for Japanese。

日文版

英文版

我向维基媒体发送了一个 HTTP 请求,我得到了一个以 XML 格式形成的结果。当我尝试在 API Sandbox 网页上发送请求并获得结果时,结果中没有字符损坏。

但是当我在 Java 中得到结果时,结果包括字符损坏。

我无法在 XML 文件中分配特定的字符代码。

如何为结果分配特定的字符代码?我该如何解决我的问题?

  try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db
                .parse(new URL(
                        "http://ja.wikipedia.org/w/api.php?action=query&prop=categories&format=xml&cllimit=10&titles="
                                + key).openStream());
        Element root = doc.getDocumentElement();
        NodeList queryList = root.getChildNodes();
        Node query = queryList.item(0);
        if (query instanceof Element) {
            Element queryEle = (Element) query;
            NodeList pagesList = queryEle.getChildNodes();
            Node pgs = pagesList.item(0);
            if (pgs instanceof Element) {
                Element pagesElement = (Element) pgs;
                NodeList pageList = pagesElement.getChildNodes();
                Node page = pageList.item(0);
                if (page instanceof Element) {
                    Element pageElement = (Element) page;
                    String title = pageElement.getAttribute("title");
                    title = new String(title.getBytes("UTF-8"), "UTF-8");
                }
            }
        }
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    }

现在我发送一个请求,我得到一个页面标题为“大学”的结果。但是在Java中,它显示“??”。

我将上述代码用于 Android 应用程序。

4

1 回答 1

0

title = new String(title.getBytes("UTF-8"), "UTF-8");可以省略。

它对我有用,因为 key=1 (接收 UTF-8)。不过,我有一台 UTF-8 Linux PC。也许你没有在 UTF-8 上下文中输出。尝试将文档写入文件。

你可以做更多的检查:

URLConnection connection = new URL("...").openConnection();
... connection.getContentEncoding();
... connection.getContentType();
InputStream in = connection.openStream();
于 2013-01-06T11:26:36.950 回答