标签:
一、测试
服务端使用GB2312编码
客户端使用utf-8接收
public class test {
public static void main(String[] args){
String str="哈哈";
try {
byte[] b1 = str.getBytes("GB2312");
byte[] b2 = str.getBytes("UTF-8");
for (int i = 0; i < b1.length; i++) {
System.out.print(b1[i]);
}
System.out.println();
for (int i = 0; i < b2.length; i++) {
System.out.print(b2[i]);
}
System.out.println();
System.out.println(new String(b1));
System.out.println(new String(b1, "UTF-8"));
System.out.println(new String(b2, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行一下例子,你会发现,结果是:
-71-2-71-2
-27-109-120-27-109-120
哈哈
????
哈哈
结论:
1、服务端用什么格式,客户端就要用什么格式去接收,否则会出现乱码。
2、只要两边格式一样,传输中格式的变化,不会出现乱码。
二、 InputStreamReader()方法是字节流通向字符流的桥梁,它使用指定的 charset读取字节并将其解码为字符
if (conn.getResponseCode()==200){
InputStreamReader isr=new InputStreamReader(conn.getInputStream(),"utf-8");
StringBuffer sb=new StringBuffer();
char buf[]=new char[1024];
int len=0;
while ((len = isr.read(buf)) != -1)
{
sb.append(new String(buf, 0, len));
}
isr.close();
}
标签:
原文地址:http://www.cnblogs.com/324sige/p/5727005.html