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