当前位置: 代码迷 >> Android >> json在客户端和服务器端传中文乱码的有关问题
  详细解决方案

json在客户端和服务器端传中文乱码的有关问题

热度:64   发布时间:2016-04-28 07:42:19.0
json在客户端和服务器端传中文乱码的问题

客户端封装的json

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(strUrl);
StringEntity entity = new StringEntity(json);
entity.setContentType("application/json");
entity.setContentEncoding("utf-8");
post.setEntity(entity);
     HttpResponse responString = client.execute(post);


服务器端接受数据:

try {
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
 String line = "";

 StringBuilder sb = new StringBuilder();
 while((line = br.readLine())!=null){
 sb.append(line);
 }
 System.out.println("diaryjson:"+sb.toString());
 } catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("diaryjson receive failure!!!!");
}  


传递的数据中有中文,服务器端获取到的是乱码,如何解决?!

------解决方案--------------------
URLDecoder.decode是解码把。
LZ把发送的数据用URLEncoder.encode编码下,在接收到时再用URLDecoder.decode解码下
------解决方案--------------------
引用:
Quote: 引用:

URLDecoder.decode是解码把。
LZ把发送的数据用URLEncoder.encode编码下,在接收到时再用URLDecoder.decode解码下


网上说的这些个方法我都试过了!!!你说的方法我也试过了!!!
这是生成json的方法最后返回的就是你说的。

public String MakeDiaryJson(String title,String context,String createtime,String lastmodifytime, int user_id) throws Exception{
String diaryjson="";
JSONObject json = new JSONObject();
try {
//diary中存入日记标题
json.put("title", title);
//diary中存入日记内容
json.put("context", context);
//diary中存入日记创建时间
json.put("createtime", createtime);
//diary中存入日记最后一次修改时间
json.put("lastmodifytime", lastmodifytime);
//diary中存入日记外键,就是这篇日记是属于哪个用户的
json.put("user_id", user_id);
diaryjson = json.toString();
URLDecoder.decode(diaryjson,"utf-8");
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.i("JSonInfo:", "MakeDiaryJson create failure!!!!");
}
return URLDecoder.decode(diaryjson,"utf-8");
};

服务器的代码:

public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("execute()方法被执行了!!!");
 try {
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
  
 String line = "";
 StringBuilder sb = new StringBuilder();
 while((line = br.readLine())!=null){
 sb.append(line);
 }
 System.out.println("diaryjson:"+URLDecoder.decode(sb.toString(),"utf-8"));

 } catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("diaryjson receive failure!!!!");

}  



return URLDecoder.decode(diaryjson,"utf-8");//这句是解码代码,发送时用编码
  相关解决方案