如何在JMeter中将附件编码为Base64?

6
我正在尝试使用以下脚本在Jmeter中对文件进行Base64编码,以测试Web服务:
String file = FileUtils.readFileToString(new File("${filepath}"), "UTF-8");
vars.put("file", new String(Base64.encodeBase64(file.getBytes("UTF-8"))));

这对于纯文本文件可以正常工作,但对于其他文件类型无法正确处理。

我该如何使其适用于其他文件类型?

6个回答

8

Jmeter有许多选项可以将变量转换为“Base64”,以下是一些选项

  1. Bean shell 前置处理器
  2. BeanShell 后置处理器
  3. BeanShell 取样器。

下面是用于在“Bean shell前置处理器”中将变量转换为Base64的“bean shell”代码

import org.apache.commons.codec.binary.Base64;

String emailIs= vars.get("session");

byte[] encryptedUid = Base64.encodeBase64(emailIs.getBytes());
vars.put("genStringValue",new String(encryptedUid));

示例:

Base64编码前:jdwqoeendwqqm12sdw

Base64编码后:amR3cW9lZW5kd3FxbTEyc2R3

使用Jmeter转换:

图片描述

图片描述

图片描述 使用Base64网站转换:

图片描述


1

由于Groovy现在是每个JMeter Sampler、Pre- & PostProcessor、Listener、Assertion等中首选的JSR223脚本语言,因此这项任务非常容易。

def fileAsBase64 = new File("${filepath}").bytes.encodeBase64().toString()
vars.put("file", fileAsBase64)

或者作为一行代码:

vars.put("file", new File("${filepath}").bytes.encodeBase64().toString())

就是这样。


1

使用函数${__base64Encode(nameofthestring)}对字符串进行编码,使用${__base64Decode(nameofthestring)}对字符串进行解码。


0

另一种方法是直接在用户定义变量中创建Groovy函数

${__groovy(new File(vars.get("filepath")).bytes.encodeBase64().toString(),)}

0

我尝试了以下方法,但没有成功。 byte[] bytes = FileUtils.readFileToByteArray(new File(("${filepath}").getBytes())); vars.put("file",new String(Base64.encodeBase64(bytes))); - BlueStar

0

试试这个

import org.apache.commons.codec.binary.Base64;
String forEncoding = vars.get("userName") + ":" + vars.get("passWord");
byte[] token = Base64.encodeBase64(forEncoding.getBytes());
vars.put("token", new String(token));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接