1. 程式人生 > >HttpClient用HttpPost傳輸中文字串亂碼

HttpClient用HttpPost傳輸中文字串亂碼

public static String getHttpRequestString(String url,String body) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        StringEntity stringEntity = new StringEntity(body);
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        HttpResponse response = client.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        StringBuffer jsonString = new StringBuffer();
        while((line = bufferedReader.readLine()) != null) {
            jsonString.append(line);
        }
        return jsonString.toString();
    }

這是最初的程式碼,如果傳輸的body有中文漢字的話,如果對方設定的格式是UTF-8,那麼他接收到的字元是亂碼,

stringEntity.setContentEncoding("UTF-8");
加上這樣一句程式碼,設定下格式就好了。