繁体   English   中英

如何用UTF-8读取InputStream?

[英]How to read a InputStream with UTF-8?

欢迎大家

我正在开发一个Java应用程序,它从Internet调用PHP,它给我一个XML响应。

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

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

这是我用来从PHP中解析XML文件的代码。

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

        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"); 

当你从你的InputStream读取byte[] s时。 创建字符串时,传入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)


@Amir Pashazadeh

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

Document doc = db.parse(new InputSource(new InputStreamReader(in, "UTF-8")));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM