Android character garbled problem handling, android garbled
Run the code in the Android Web HTML Viewer
Garbled characters are found in the html source code. The reason is obvious: charset = "gb2312"
The default character set for android is "UTF-8"
Public class StreamTools {/*** converts the content of the input stream into a String ** @ param is * @ return */public static String readInputStream (InputStream is) {try {ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); return new String (result);} catch (Exception e) {e. printStackTrace (); return null ;}}}
Modify the code line marked above:
Return new String (result, "gb2312 ");
The effect after running is as follows:
However, this modification is not intelligent enough. If UTF-8 encoding is used, garbled characters may occur. Continue to modify the Code as follows:
Package com.wuyudong.html viewer. utils; import java. io. byteArrayOutputStream; import java. io. inputStream; public class StreamTools {/*** converts the content of the input stream to a String ** @ param is * @ return */public static String readInputStream (InputStream is) {try {ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); String str = new String (result); // try to parse the String if (str. contains ("gb2312") {return new String (result, "gb2312");} else if (str. contains ("UTF-8") {return str;} else {return null;} // return new String (result, "gb2312");} catch (Exception e) {e. printStackTrace (); return null ;}}}