你的分享就是我们的动力 ---﹥

HttpPost发送JSON数据中文乱码问题。

时间:2013-03-08 09:34来源:www.chengxuyuans.com 点击:
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);
   }

共同学习,共同进步,不对之处还望指正。

本文地址http://www.chengxuyuans.com/Android/51173.html