您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection中文乱码分析和解决

2017-12-01 17:19 453 查看

HttpURLConnection中文乱码分析和解决

产生中文乱码一般都是编码格式不匹配导致的,例如后台使用UTF-8编码格式,而移动端在接收数据时采用Iso 或者 GBK等格式,而往往我们所使用的网络编程工具在我们步明确指定编码格式的情况下给我们指定的默认格式并非UTF-8.

比如下面这段代码就会导致中文乱码

URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
result = sb1.toString();


在这样的操作下,有可能会出现接收到的中文是乱码的,比如后台返回的格式是”UTF-8”,接收到的中文就会是乱码

解决方法进行转码

InputStream input = conn.getInputStream();
InputStreamReader reader=new InputStreamReader(input,"UTF-8");
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = reader.read()) != -1) {
sb1.append((char) ss);
result = sb1.toString();


**注:**Volley在后台步明确指定编码格式的情况下也会默认采用ISO-8859-1格式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络编程 编码 乱码