[英]How to zip and encode in base64 an xml in Karate?
let's say I have an xml from a file or saved in a variable in the feature file.假设我有一个来自文件的 xml 或保存在功能文件的变量中。
How do I zip it then encode it in base64 using Karate?我如何 zip 然后使用空手道将其编码为 base64?
I tried using Java, but with no success: I saved my xml in a variable first, then passed it to the Java methods below:我尝试使用 Java,但没有成功:我先将 xml 保存在一个变量中,然后将其传递给下面的 Java 方法:
def xmlString = read('path/to/xmlName.xml')
First try , I get the error that I cannot convert Xml to String -> Cannot convert 'xml content placeholder'(language: Java, type: com.intuit.karate.graal.JsXml) to Java type 'java.lang.String': Invalid or lossy primitive coercion.首先尝试,我收到无法将 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);
}
Second try , I get the same error as above:第二次尝试,我得到与上面相同的错误:
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);
}
The first Java method works.第一个 Java 方法有效。 I just needed to pass it the relative path of my actual file instead of passing the karate variable "def xmlString = read('path/to/xmlName.xml')"我只需要将我的实际文件的相对路径传递给它,而不是传递空手道变量“def xmlString = read('path/to/xmlName.xml')”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.