当前位置: 代码迷 >> PB >> XML压缩传输解决方法
  详细解决方案

XML压缩传输解决方法

热度:160   发布时间:2016-04-29 09:34:36.0
XML压缩传输
功能说明:Java servlet 把XML数据压缩后发送到PB用户端,PB收到数据后解压出来.

传输要经过Base64编码.

问题是:能收到数据但是解压不出来.想请教大家或者有什么好的办法?

PB可以用"zlibwapi.DLL" 解压

////////////////////////////// 

Java CODE:

//压缩数据
if(strXML !=null){
byte[] byte_XMLData=null;

StringZip strZip =new StringZip();
byte_XMLData =StringZip.ZipString(strXML.toString());

String encode = Base64.getEncodedText(byte_XMLData);  

//输出数据
PrintWriter outputWriter =null;
try {
outputWriter = res.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
outputWriter.println(encode.toString());
outputWriter.close();
}

package org.peng.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class StringZip{
/**
* 压缩字符串为 byte[]
* 保存为字符串
*
* @param str 压缩前的文本
* @return
*/
public static final byte[] ZipString(String str) {
if(str == null)
return null;

byte[] compressed;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null;
try {
out = new ByteArrayOutputStream();
zout = new ZipOutputStream(out);
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes());
zout.closeEntry();
compressed = out.toByteArray();
} catch(IOException e) {
compressed = null;
} finally {
if(zout != null) {
try{zout.close();} catch(IOException e){}
}
if(out != null) {
try{out.close();} catch(IOException e){}
}
}
return compressed;
}

/**
* 将压缩后的 byte[] 数据解压缩
*
* @param compressed 压缩后的 byte[] 数据
* @return 解压后的字符串
*/
public static final String unZipString(byte[] compressed) {
if(compressed == null)
return null;

ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
ZipInputStream zin = null;
String decompressed;
try {
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(compressed);
zin = new ZipInputStream(in);
@SuppressWarnings("unused")
ZipEntry entry = zin.getNextEntry();
byte[] buffer = new byte[1024];
int offset = -1;
while((offset = zin.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
decompressed = null;
} finally {
if(zin != null) {
try {zin.close();} catch(IOException e) {}
}
if(in != null) {
try {in.close();} catch(IOException e) {}
}
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
return decompressed;
}
}

////////////////////////////// 
package org.peng.util;

import java.io.IOException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {  
 
  public static String getEncodedText(byte[] bytes) {  

  try {  
  BASE64Encoder encoder = new BASE64Encoder();  
  String text = encoder.encode(bytes);  
  return text;  
  } catch (Exception e) {  
  e.printStackTrace();  
  return null;  
  }  
   
  }  
   
  public static byte[] decode(String src)  
  {  
  相关解决方案