8

欢迎大家

我正在开发一个 Java 应用程序,它从互联网上调用一个 PHP,它给了我一个 XML 响应。

响应中包含这个词:“Próximo”,但是当我解析 XML 的节点并将响应获取到 String 变量中时,我收到这样的词:“Próximo”。

我确定问题在于我在 Java 应用程序中使用了不同的编码,然后是 PHP 脚本的编码。然后,我想我必须将编码设置为与您的 PHP xml 中的 UTF-8 相同

这是我用来从 PHP 获取 XML 文件的代码。

¿ 我应该在此代码中更改什么以将编码设置为 UTF-8?(请注意,我没有使用缓冲阅读器,我使用的是输入流)

        InputStream in = null;
        String url = "http://www.myurl.com"
        try {                              
            URL formattedUrl = new URL(url); 
            URLConnection connection = formattedUrl.openConnection();   
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();               
            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
                in = httpConnection.getInputStream();   

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                     
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(in);
            doc.getDocumentElement().normalize();             
            NodeList myNodes = doc.getElementsByTagName("myNode"); 
4

1 回答 1

9

当您从中InputStream读取byte[]时。创建字符串时,传入CharSet“UTF-8”。例子:

byte[] buffer = new byte[contentLength];
int bytesRead = inputStream.read(buffer);
String page = new String(buffer, 0, bytesRead, "UTF-8");

请注意,您可能希望将缓冲区设置为合理的大小(如 1024),并不断调用inputStream.read(buffer).


@阿米尔帕沙扎德

是的,您也可以使用 InputStreamReader,并尝试将 parse() 行更改为:

Document doc = db.parse(new InputSource(new InputStreamReader(in, "UTF-8")));
于 2012-07-22T19:09:52.337 回答