Android中程序乱码问题解决

有一次,做某一个网络App项目时,遇到了一个中文乱码的问题,修改Android Studio的编码的格式还是换编译的编码格式都不能解决问题。经过不断探索、不停Google,终于解决了问题。

原来是Java的输入流的问题。

以下是原来的获取网页Html的函数:

    public static String getHtml( HttpClient httpClient, String url ) throws Exception {
        HttpGet get =new HttpGet(url);
        HttpResponse response = httpClient.execute(get);
        int ch;
        InputStream inputStream = response.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        while((ch = inputStream.read()) != -1) {
            sb.append((char) ch);
        }
        String html = sb.toString();
        // android.util.Log.i("Get", html);
        return html;
    }

经过修改,应该为以下的代码:

    public static String getHtml( HttpClient httpClient, String url ) throws Exception {
        HttpGet get =new HttpGet(url);
        HttpResponse response = httpClient.execute(get);
        int ch;
        InputStream inputStream = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(inputStream,"UTF-8"));
        String data = "";
        StringBuilder sb = new StringBuilder();
        while((data = br.readLine()) != null) {
            sb.append(data);
            sb.append("\n");
        }
        String html = sb.toString();
        // android.util.Log.i("Get", html);
        return html;
    }


发布了26 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sad490/article/details/79369533