0

我正在通过 HTTP-REDIRECT 绑定机制实现 SAMLSLO。使用 deflate-inflate 工具会给我一个 DataFormatException 错误的标题检查。

我试过这个作为一个独立的。虽然我没有在这里得到 DataFormatException,但我观察到整个消息没有被返回。

    import java.io.UnsupportedEncodingException;
    import java.util.logging.Level;
    import java.util.zip.DataFormatException;
    import java.util.zip.Deflater;
    import java.util.zip.Inflater;


    public class InflateDeflate {
    public static void main(String[] args) {
    String source = "This is the SAML String";
            String outcome=null;
    byte[] bytesource = null;
    try {
        bytesource = source.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    int byteLength = bytesource.length;
    Deflater compresser = new Deflater();
    compresser.setInput(bytesource);
    compresser.finish();

    byte[] output = new byte[byteLength];
    int compressedDataLength = compresser.deflate(output);
    outcome = new String(output);
    String trimmedoutcome = outcome.trim();
    //String trimmedoutcome = outcome;  // behaves the same way as trimmed;
            // Now try to inflate it
    Inflater decompresser = new Inflater();
    decompresser.setInput(trimmedoutcome.getBytes());
    byte[] result = new byte[4096];
    int resultLength = 0;
    try {
        resultLength = decompresser.inflate(result);
    } catch (DataFormatException e) {
        e.printStackTrace();
    }
    decompresser.end();
    System.out.println("result length ["+resultLength+"]");
    String outputString = null;
    outputString = new String(result, 0, resultLength);
    String returndoc = outputString;
    System.out.println(returndoc);
    }

    }

令人惊讶的是,我得到的结果是 [22] 字节,原来是 [23] 字节,膨胀后“g”丢失了。

我在这里做一些根本错误的事情吗?

4

1 回答 1

0

Java 的 String 是 CharacterSequence(一个字符是 2 个字节)。使用new String(byte[])可能无法正确地将您的 byte[] 转换为 String 表示形式。至少您应该指定一个字符编码new String(byte[], "UTF-8")以防止无效的字符转换。

下面是一个压缩和解压的例子:

import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
...

byte[] sourceData; // bytes to compress (reuse byte[] for compressed data)
String filename; // where to write
{
    // compress the data
    Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
    deflater.setInput(sourceData);
    deflater.finish();
    int compressedSize = deflater.deflate(data, 0, sourceData.length, Deflater.FULL_FLUSH);

    // write the data   
    OutputStream stream = new FileOutputStream(filename);
    stream.write(data, 0, compressedSize);
    stream.close();
}

{
    byte[] uncompressedData = new byte[1024]; // where to store the data
    // read the data
    InputStream stream = new InflaterInputStream(new FileInputStream(filename)); 
    // read data - note: may not read fully (or evenly), read from stream until len==0
    int len, offset = 0;
    while ((len = stream.read(uncompressedData , offset, uncompressedData .length-offset))>0) {
        offset += len;
    }           
    stream.close();
}
于 2013-05-23T20:15:42.150 回答