Androidのプログラムの文字化け問題は解決します。

1510 ワード

ある時、あるネットアプリのプロジェクトをする時、中国語の文字化けの問題に出会いました。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("
"); } String html = sb.toString(); // android.util.Log.i("Get", html); return html; }