java 和 python decodeBase64ZippedString encodeBase64ZippedString

发布时间 2023-05-26 15:25:15作者: vx_guanchaoguo0

java

package com.example;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Base64zip {
    public static final int ZIP_BUFFER_SIZE = 8192;
    public static final String XML_ENCODING = "UTF-8";

    public static String decodeBase64ZippedString(String loggingString64) throws IOException {
        if (loggingString64 == null || loggingString64.isEmpty()) {
            return "";
        }
        StringWriter writer = new StringWriter();
        byte[] bytes64 = Base64.decodeBase64(loggingString64.getBytes());
        ByteArrayInputStream zip = new ByteArrayInputStream(bytes64);
        try (GZIPInputStream unzip = new GZIPInputStream(zip, Base64zip.ZIP_BUFFER_SIZE); BufferedInputStream in = new BufferedInputStream(unzip, Base64zip.ZIP_BUFFER_SIZE); InputStreamReader reader = new InputStreamReader(in, Base64zip.XML_ENCODING)) {

            char[] buff = new char[Base64zip.ZIP_BUFFER_SIZE];
            for (int length; (length = reader.read(buff)) > 0; ) {
                writer.write(buff, 0, length);
            }
        }
        return writer.toString();
    }

    public static String encodeBase64ZippedString(String in) throws IOException {
        Charset charset = Charset.forName(Base64zip.XML_ENCODING);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        try (Base64OutputStream base64OutputStream = new Base64OutputStream(baos); GZIPOutputStream gzos = new GZIPOutputStream(base64OutputStream)) {
            gzos.write(in.getBytes(charset));
        }
        return baos.toString();
    }
}

python