When retrieving data from a Web page, you must pay attention to Character Set Issues. Careless handling is indeed miserable. For example, when you use a URL Connection to package InputStream as a bytes stream (so that it can be directly saved as a String), you must add the charsetName parameter. The function prototype is InputStreamReader (InputStream in, String charsetName) // create an InputStreamReader that uses the specified character set. Set this parameter to the character set used by the corresponding webpage. (Usually UTF-8 or GBK) for example.
URL url = new URL (urlString); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (80000); conn. setRequestMethod ("GET"); conn. connect (); // convert the input stream to the primary stream BufferedReader bufReader = new BufferedReader (new InputStreamReader (conn. getInputStream (), "UTF-8"); // assume that the data has only one row of String result = bufReader. readLine ();
However, if the character set is not set when the volume stream is packaged, and the attempt to obtain the original data before conversion is still problematic. I think the reason is that when the data obtained by the byte stream is converted to the data in the bytes stream, it involves encoding byte as char. When the default GBK encoding is used, in the UTF8 byte stream, some bytes cannot be correctly decoded and are converted into garbled characters of GBK, that is, the byte array (if any) in InputStreamReader ), it is inconsistent with that returned by HttpURL.
URL url = new URL (urlString); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (80000); conn. setRequestMethod ("GET"); conn. connect (); // convert the input stream to the primary stream BufferedReader bufReader = new BufferedReader (new InputStreamReader (conn. getInputStream () //, "UTF-8" does not have this parameter will occur); // assume that the data has only one line of String result = bufReader. readLine (); String newResult = new String (result. getBytes ("GBK"), "UTF-8"); // attempts to convert UTF-8 data from a web page to GBK, at which point some data cannot be converted correctly