最近比较倒霉,也碰到了乱码问题,这里还是记录一下,方便以后的学习。话不多说,进入正题。
问题描述:
一台安卓设备通过调用WebService接口,返回得到一串Json字符串,为了让通信的流量减少,这里采用了Java的GZip压缩,结果安卓得到返回的字符串出现乱码。
分析问题产生原因:
1. Tomcat中传递字符都是以ISO-8859-1的编码进行的。
2. 本机中的Eclipse工作空间默认编码是UTF-8。
3. 在压缩的过程中,字符串应该是以UTF-8变成字符数组的,而原来代码中只是按编码的缺省值进行转换。现在代码发布在ApechaAxis2上,是以ISO-8859-1编码,不进行特定转换,原来的UTF-8字符就以ISO-8859-1编码进行表示,所以才出错。
问题解决代码:(注意:解决前与解决后的代码差别只是加了一行有注释的代码)
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.json.JSONObject;
/**
* Gzip压缩解压编码
* @author lin-xiandong
*
*/
public class GZipUtil {
public static String compress(String str){
String ret = "";
if (null == str || str.length() <= 0) {
ret = str;
}else{
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes("UTF-8"));//修复乱码所在
gzip.close();
ret = out.toString("ISO-8859-1");
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n = 0;
while ((n = gzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString("UTF-8");
}
public static String getCompressJsonStr(JSONObject jObj){
JSONObject resultJson = new JSONObject();
String result = null;
try {
result = GZipUtil.compress(jObj.toString());
resultJson.put("result", result);
} catch (Exception e) {
e.printStackTrace();
}
return resultJson.toString();
}
}