繁体   English   中英

如何在空手道中将 zip 编码为 base64 和 xml?

[英]How to zip and encode in base64 an xml in Karate?

假设我有一个来自文件的 xml 或保存在功能文件的变量中。

我如何 zip 然后使用空手道将其编码为 base64?

我尝试使用 Java,但没有成功:我先将 xml 保存在一个变量中,然后将其传递给下面的 Java 方法:

  • def xmlString = read('path/to/xmlName.xml')

首先尝试,我收到无法将 Xml 转换为字符串的错误 -> 无法将“xml 内容占位符”(语言:Java,类型:com.intuit.karate.graal.JsXml)转换为 Java 类型“java.lang.String” :无效或有损的原始强制转换。

    public static String encode64ZippedXml(String xml) throws IOException {
       File file = new File(xml);
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            try (FileInputStream fis = new FileInputStream(file)) {
                zos.putNextEntry(new ZipEntry(file.getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
            }
        }
        byte[] bytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    }

第二次尝试,我得到与上面相同的错误:

    public static String zipEncodeXml (String xmlFile, String xmlFilePath) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);

        ZipEntry entry = new ZipEntry(xmlFile);
        zos.putNextEntry(entry);

        byte[] xmlData = Files.readAllBytes(Paths.get(xmlFilePath));
        zos.write(xmlData);

        zos.closeEntry();
        zos.close();

        byte[] zipData = baos.toByteArray();
        return Base64.getEncoder().encodeToString(zipData);
    }

第一个 Java 方法有效。 我只需要将我的实际文件的相对路径传递给它,而不是传递空手道变量“def xmlString = read('path/to/xmlName.xml')”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM