`
randor
  • 浏览: 12513 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

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);
   }

共同学习,共同进步,不对之处还望指正。
分享到:
评论
1 楼 zz4165456zz 2013-11-06  
非常感谢,解决了我的问题。

相关推荐

Global site tag (gtag.js) - Google Analytics