最近有个项目在使用HttpURLConnection进行网络请求,返回结果出现了部分中文乱码的情况,而且只是一部分,很郁闷,最后慢慢分析,终于找到原因!!
1. 之前的写法
主要原因是因为边读服务器数据边将byte转成utf8,utf8编码是3个字节对应一个字符,但万一只读了一个字节或者不为3的倍数怎么办?这样强转编码就会导致乱码出现,比如出现“?”等,正确的做法是先缓存完所有字节,再一次性转换编码!
//获取请求数据
InputStream inputStream = httpURLConnection.getInputStream();
int count = 0;
StringBuilder stringBuilder = new StringBuilder();
byte[] buffer = new byte[4096];
while ((count = inputStream.read(buffer)) != -1) {
stringBuilder.append(new String(buffer, 0, count, "utf-8"));
}
inputStream.close();
httpURLConnection.disconnect();
//将结果转成String
String result = stringBuilder.toString();
2. 改正
用ByteArrayOutputStream先缓存,最后再统一转换。
//获取请求数据
InputStream inputStream = httpURLConnection.getInputStream();
int count = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
while ((count = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, count);
}
byte[] data = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
inputStream.close();
httpURLConnection.disconnect();
//将结果转成String
String result = new String(data, 0, data.length, "utf-8");
网友评论