android端和web端通信中文乱码问题

本文介绍了一种解决Android端与Web端通信时字符编码不一致导致的乱码问题的方法。通过在两端统一采用UTF-8编码,并对传递的字符串进行相应的编码转换,确保了数据传输的正确性。
第一步:


把Android端和web端的工程编码方式都改为utf-8


第二步:
在Android端对传递的参数进行如下处理

将要使用get方式传递的字符串处理一下在传递

start = URLEncoder.encode(start, "utf-8")

例如:

String path ="http://"+getpath+"/KuaiDi3/BusTime_Servlet?start="+URLEncoder.encode(start, "utf-8")+"&end="+URLEncoder.encode(end, "utf-8")+"&date="+URLEncoder.encode(date, "utf-8");






第三步:


在web端对接收的参数进行如下处理
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("urf-8");
同时一定要进行如下处理,如果不进行如下处理,还是会出错的,切记!!!


String start = request.getParameter("start");
String end = request.getParameter("end");

String date = request.getParameter("date");


String start = new String(start.getBytes("ISO-8859-1"),"utf-8");
String end = new String(end.getBytes("ISO-8859-1"),"utf-8");

String date = new String(date.getBytes("ISO-8859-1"),"utf-8");

方法封装:

android端:

/*
 * 该方法把字符串转码为UTF_8
 * 解决android端与web端通信字符串乱码问题
 * */
public class StringTo_UTF_8 {
<span style="white-space:pre">	</span>public static String my_Encode(String instring)  {
 <span style="white-space:pre">		</span>String outString = null;
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">		</span>outString = URLEncoder.encode(instring, "utf-8");
<span style="white-space:pre">		</span>} catch (UnsupportedEncodingException e) {
<span style="white-space:pre">			</span>// TODO Auto-generated catch block
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>return outString;
<span style="white-space:pre">	</span>}
}


web端:

public class Web_UTF_8 {
<span style="white-space:pre">	</span>public static String to_UTF_8(String inString){
<span style="white-space:pre">		</span>String outString = null;
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">		</span>outString = new String(inString.getBytes("ISO-8859-1"),"utf-8");
<span style="white-space:pre">		</span>} catch (UnsupportedEncodingException e) {

<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">			</span>};


<span style="white-space:pre">		</span>return outString;
<span style="white-space:pre">	</span>}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值