欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

android POST數(shù)據(jù)遇到的UTF-8編碼(亂碼)問題解決辦法

 更新時(shí)間:2014年04月18日 08:42:10   作者:  
這篇文章主要介紹了android POST數(shù)據(jù)遇到的UTF-8編碼(亂碼)問題解決辦法,需要的朋友可以參考下

今天遇到這樣一個(gè)bug:客戶端POST到服務(wù)器的一段數(shù)據(jù)導(dǎo)致服務(wù)器端發(fā)生未知異常。服務(wù)器端確認(rèn)是編碼轉(zhuǎn)換錯(cuò)誤。于是截取網(wǎng)絡(luò)數(shù)據(jù)包進(jìn)行分析,發(fā)現(xiàn)客戶端POST的json數(shù)據(jù)中包含下面一段(hex形式):

復(fù)制代碼 代碼如下:
... 61 64 20 b7 20 52 69 63 ...

問題就出在這個(gè)b7上。查閱Unicode代碼表后發(fā)現(xiàn),U+00b7是MIDDLE DOT,它的UTF-8表現(xiàn)形式應(yīng)該是c2 b7,但為何客戶端發(fā)送的數(shù)據(jù)中它變成了b7?

由于系統(tǒng)使用了ormlite、gson和async-http幾個(gè)庫,于是逐一排查。最后發(fā)現(xiàn)原來是向服務(wù)器發(fā)送數(shù)據(jù)時(shí)沒有指定文字編碼,導(dǎo)致async-http(實(shí)際是apache common http client)將數(shù)據(jù)以ISO-8559-1格式發(fā)送,U+00b7被編碼成b7,然后服務(wù)器試圖使用UTF-8解碼時(shí)發(fā)生錯(cuò)誤。

出錯(cuò)的代碼片段如下:

復(fù)制代碼 代碼如下:

Gson gson = new Gson();
String json = gson.toJson(data);
StringEntity entity = new StringEntity(json);
httpClient.post(context, url, entity, "application/json", new TextHttpResponseHandler() ... );

第三行new StringEntity(json)時(shí)沒有指定編碼導(dǎo)致錯(cuò)誤。改正后如下:
復(fù)制代碼 代碼如下:

Gson gson = new Gson();
String json = gson.toJson(data);
StringEntity entity = new StringEntity(json, "utf-8");
httpClient.post(context, url, entity, "application/json;charset=utf-8", new TextHttpResponseHandler() ... );

相關(guān)文章

最新評論