如何压缩和base64一个org.w3c.dom.Document

时间:2017-11-10 10:47:03

标签: java dom base64 zip

我有一个org.w3c.dom.Document并且必须对其进行压缩和base64编码,以便通过HTTP / HTTPS使用EBICS协议发送它 我试过了

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Source xmlSource = new DOMSource(doc);
    Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    InputStream inflated_stream = new InflaterInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
    final byte[] bytes64bytes = Base64.encodeBase64(IOUtils.toByteArray(inflated_stream));
    OrderData = new String(bytes64bytes);

但获得例外

java.util.zip.ZipException: incorrect header check
        at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
        at java.io.FilterInputStream.read(FilterInputStream.java:107)
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:999)
        at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:218)

2 个答案:

答案 0 :(得分:0)

我没试过这个,但是下面没有做你需要的吗?

OutputStream outputStream = new ZipOutputStream(new ByteArrayOutputStream());

我认为您的问题可能归结为使用InflaterInputStream - 您是不是想 deflate 此流?如果您只是将InflaterInputStream更改为DeflaterInputStream

,则代码可能会有效

答案 1 :(得分:0)

更改

import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class)
@PrepareForTest( ResourceConfig.class )
public class StackOverflowTest {


  @Test
  public void toStackOvflow2() throws Exception {

    ResourceConfig resConf = mock(ResourceConfig.class);
    whenNew(ResourceConfig.class).withNoArguments().thenReturn(resConf);

    //WHATEVER...
  }

}

InputStream inflated_stream = new InflaterInputStream(new ByteArrayInputStream(outputStream.toByteArray()));

解决了这个问题 感谢