HttpPost發送JSON數據中文亂碼問題。

Android移動終端通過 HttpPost發送JSON數據時出現中文亂碼問題的解決方案。通常都用UTF-8 編碼。

1、客戶端 postData爲JSON數據JSONObject.
注意點:發送和接收時轉碼。
public static String httpPostData(String uri, int requestTimeOut, String postData) {
String retStr = "failure";
int tmout = 5;
if (requestTimeOut > 0){
tmout = requestTimeOut;
}
try {
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("charset", "UTF-8");
    HttpConnectionParams.setConnectionTimeout(httpParams,tmout * 1000);  //毫秒
    HttpConnectionParams.setSoTimeout(httpParams, tmout * 1000);    
HttpClient httpClient = new DefaultHttpClient(httpParams);

HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(postData.toString(),"UTF-8"));
HttpResponse response;
response = httpClient.execute(httpPost);
//檢驗狀態碼,如果成功接收數據
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
retStr = EntityUtils.toString(response.getEntity(),"UTF-8");
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
System.out.println("httpPostData() return:" + retStr);
return retStr;
}



2、WEB SERVLET
我用的是Spring3.1框架
注意點:BufferedReader取數時一定要轉碼。環境不同你可以試着轉成GBK碼試試。
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ServiceException {
    request.setCharacterEncoding("UTF-8"); //避免中文亂碼 POST方式提交 
    response.setContentType("text/json;charset=UTF-8");
        String responseData="[{}]"; //JSONArray String
            // 讀取請求JSON數據       
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
        String line = "";
        StringBuilder sbf = new StringBuilder();
        while((line = br.readLine())!=null){
            sbf.append(line);
        }
        String postData = sbf.toString();
        if(postData==null || "".equals(postData)){
        postData = "{}"; //JSON數據
         }
        System.out.println("postData:" + postData);
   }

共同學習,共同進步,不對之處還望指正。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章