How to read InputStream with UTF-8?

Welcome everyone

I am developing a Java application that calls PHP from the Internet, which gives me an XML response.

The answer contains this word: "Próximo", but when I parse the XML nodes and get the response into the String variable, I get the word like this: "Pr & oacute; ximo".

I am sure that the problem is that I use a different encoding in my Java application and then encode a PHP script. Then, I suppose, I should set the encoding the same way as in your PHP xml, UTF-8

This is the code that I use to create an XML file with PHP.

. What should I change in this code to set the encoding to UTF-8? (note that im does not use a buffered reader, I use input stream)

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"); 
+6
source share
1 answer

When you get an InputStream , read byte[] . When you create your lines, go to CharSet for "UTF-8". Example:

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

Note that you probably want to make your buffer an incorrect size (for example, 1024) and be constantly called inputStream.read(buffer) .


@ Amir Pashazade

Yes, you can also use InputStreamReader and try changing the parse () line to:

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

Source: https://habr.com/ru/post/921081/


All Articles