【问题标题】:How to encode an attachment to Base64 in Jmeter?如何在 Jmeter 中对 Base64 的附件进行编码?
【发布时间】:2016-04-11 14:58:19
【问题描述】:

我正在尝试在 Jmeter 中将文件编码为 Base64 以使用以下脚本测试 Web 服务:

String file = FileUtils.readFileToString(new File("${filepath}"), "UTF-8");
vars.put("file", new String(Base64.encodeBase64(file.getBytes("UTF-8"))));

这适用于纯/文本文件,但不适用于其他文件类型。

我怎样才能使它适用于其他文件类型?

【问题讨论】:

    标签: web-services jmeter base64 automated-tests jmeter-plugins


    【解决方案1】:

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

    1. 豆壳预处理器
    2. BeanShell 后处理器
    3. BeanShell 采样器。

    下面是“bean shell”代码,用于“bean shell预处理器”将变量转换为Base64

    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 网站转换:

    【讨论】:

      【解决方案2】:

      由于 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())
      

      就是这样。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          您的问题来自于您在读取二进制文件时将其视为文本,这是错误的。

          使用它来读取文件:

          然后用Base64编码字节数组

          【讨论】:

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

          试试这个

          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));
          

          【讨论】:

            【解决方案6】:

            对此的替代方法是直接在用户定义的变量中创建一个 groovy 函数

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

            【讨论】:

              猜你喜欢
              • 2010-09-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-11-11
              • 2012-10-26
              • 2011-09-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多