1. 程式人生 > >Android Post Json資料亂碼問題

Android Post Json資料亂碼問題

這兩天在做註冊功能時,暱稱裡有漢字,tomcat伺服器後臺日誌及資料庫的漢字都顯示?問號。伺服器是CentOS 7.0, 將系統語言配置成 LANG=zh_CN.UTF-8,伺服器端程式碼的web.xml中已經添加了org.springframework.web.filter.CharacterEncodingFilter的Filter。結果還是亂碼,問題可能出在Android客戶端上。網上查了些資料,並嘗試了更改不同位置的程式碼,定位到了問題。

Json資料如下格式:

{"phone":"18688888888","passwd":"123456","nickname":"漢字","verifycode":"2769"}


private static final String APPLICATION_JSON = "application/json;charset=utf-8";

public static <T extends Result> T postJson(String url, String postBodyJson, Class<T> clazz) throws IOException {
        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(postBodyJson)) {
            Log.e(TAG, "url/postBodyJson should not be null");
            return null;
        }

	DefaultHttpClient httpClient = getHttpClient();
	httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);
        httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, TIMEOUT);

        HttpPost httpPost = new HttpPost(url);

        StringEntity stringEntity = new StringEntity(postBodyJson);
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
        httpPost.setEntity(stringEntity);

        httpPost.setHeader(HTTP.USER_AGENT, "xxx/1.0");
        httpPost.setHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        httpPost.setHeader("Accept", APPLICATION_JSON);

        PersistentCookieStore cookieStore = MyFragment.getInstance().getCookieStore();
        httpClient.setCookieStore(cookieStore);

        HttpResponse response = httpClient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();

        if (HttpStatus.SC_OK == code) {

            //Login succeed
            if (StringUtils.isNotEmpty(url) && url.contains(Config.REQUEST_URL_LOGIN)) {
                //Save cookies
                List<Cookie> cookies = httpClient.getCookieStore().getCookies();

                for (Cookie cookie : cookies) {
                    cookieStore.addCookie(cookie);
                }
            }

            String rspStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            Log.d(TAG, rspStr);

            T result = null;
            try {
                result = JSONHelper.parseObject(rspStr, clazz);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return result;

        } else if (HttpStatus.SC_UNAUTHORIZED == code) {
	    throw new UnauthorizedException("Unauthorized. Need to login again.");
	} else {
            throw new IOException("ERROR: rspCode=" + code + "-" + response.getEntity().toString());
        }
}

嘗試了增加宣告utf-8的header和stringEntity.setContentEncoding之後,問題依舊。


其中,如下一行

StringEntity stringEntity = new StringEntity(postBodyJson);

增加UTF-8編碼後,再測試資料庫和tomcat log已經變成了漢字,問題解決。

StringEntity stringEntity = new StringEntity(postBodyJson, "UTF-8"); //不帶UTF-8,漢字會是亂碼

參考:

http://blog.csdn.net/bonnshore/article/details/18327881

http://www.jb51.net/article/49132.htm

http://chaico.iteye.com/blog/1954128