我们通过Http连接网络传递中文参数时经常遇到乱码问题,这节我们将一起解决这个问题.乱码问题一般是客户端和服务端编码方式不一至造成的.
首先统一客户端和服务端的编解码方式为UTF-8.
Web服务端一般采用Tomcat服务器,Tomcat默认编码方式为ISO-8859-1,iso-8859-1是不支持中文的,也就是说不做处理,中文是一定乱码的。
代码处理可用
String userName = new String(userName.getBytes("ISO-8859-1"), "UTF-8");
更改Tomcat编码方式为UTF-8.
在TOMCAT的配置文件的server.xml中更改:
<Connector port="8080"protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
添加URIEncoding=UTF-8
Android客户端
发送Get请求,首先对请求URL地址的中文进行UTF-8编码.
String name =URLEncoder.encode("中国万岁","UTF-8");
发送Post请求,对参数也要进行UTF-8编码,方式如下:
BasicNameValuePair userNamePair = new BasicNameValuePair("userName", "李四");
BasicNameValuePair passWordPair = new BasicNameValuePair("passWord", "321");
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(userNamePair);
parameters.add(passWordPair);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
//乱码关键代码
1.UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
2.httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
注:如果在Servlet中设置request.setCharacterEncoding(“UTF-8″);上面第2行代码可以不设置.