下面是三种方式读取输入流:
1、按字符读取输入流,这种方式是把流读到字符数组中
注:8位(bit)==1个字节(Byte), 1个字符(char)==16位(bit)== 2字节(Byte), 一个汉字占2字节,也就是占1字符,所以用char数组装汉字时不会把汉字分成两半,而用byte数组装汉字时候,很可能第一次读取汉字的前一半,第二次读取汉字的后一半,固出现乱码。
char buf[] = new char[20];
int len = bufferedReader.read(buf);
while(len!=-1){
sb.append(new String(buf, 0, len));
len = bufferedReader.read(buf);
}
2、按行读取,不会出乱码,效率没测试,他们说还行
String line="";
while((line=br.readLine())!=null){
System.out.println("==========="+line);
return line;
}
br.close();
3、按字节数组读取
byte[] bytes = new byte[4096];
int i = 0;
while ((i = inputStream.read(bytes)) != -1) {
sb.append(new String(bytes,"GBK"));
bytes = new byte[4096];
android端和j2ee端交互时,设置编码格式:
httpURLConnection.setRequestProperty("Content-type", "text/html");
httpURLConnection.setRequestProperty("Accept-Charset", "GBK");
httpURLConnection.setRequestProperty("contentType", "GBK");
服务器端在action中设置编码要一致:
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("GBK");
OutputStream out = response.getOutputStream();
在struts.xml中设置:
<constant name="struts.i18n.encoding" value="gbk"></constant>
如果不行,再配置过滤器(适用struts2.2):
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>com.bohe.web.EncodeFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
加入自己的字符过滤器:
public class EncodeFilter extends StrutsPrepareAndExecuteFilter implements
Filter {
private FilterConfig config = null;
private String encoding = null;
@Override
public void init(FilterConfig config) throws ServletException {
//System.out.println("init................");
this.config = config;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("dofilter.......");
if (encoding == null) {
encoding = config.getInitParameter("encoding");
System.out.println(encoding);
}
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void destroy() {
config = null;
encoding = null;
}
}
最后,如果还不行,只能修改tomcat的server.xml配置文件了:加入URIEncoding="GBK"
<Connector port="8888" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="GBK"/>
ps:http方式访问带中文参数的都要urlencode一下,服务器会自动decode
最后发现个重复编码的问题:如果服务器端已经设置了GBK编码(response.setCharacterEncoding("GBK");),android端就不要再转GBK否则重复编码会乱码。
//BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"GBK"));