加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

实习笔记6 WebService Axis2 传递Gzip压缩后的字符串乱码问题

发布时间:2020-12-16 23:19:52 所属栏目:安全 来源:网络整理
导读:最近比较倒霉,也碰到了乱码问题,这里还是记录一下,方便以后的学习。话不多说,进入正题。 问题描述: 一台安卓设备通过调用WebService接口,返回得到一串Json字符串,为了让通信的流量减少,这里采用了Java的GZip压缩,结果安卓得到返回的字符串出现乱码

最近比较倒霉,也碰到了乱码问题,这里还是记录一下,方便以后的学习。话不多说,进入正题。

问题描述:

一台安卓设备通过调用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();
	}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读