最近比较倒霉,也碰到了乱码问题,这里还是记录一下,方便以后的学习。话不多说,进入正题。
问题描述:
一台安卓设备通过调用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,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(); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。