Http网络传递参数中文乱码问题


我们通过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行代码可以不设置.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值