You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LoadRunner 12.60如何对文本做gzip压缩并转存为变量/参数?

LoadRunner实现JSON字段单独Gzip压缩+Base64编码

核心思路

你需要的是JSON单个字段值的独立压缩编码,而非整个请求体的gzip压缩,因此不能使用web_custom_request的ContentEncoding=gzip参数(该参数会将整个请求体转为二进制,破坏JSON结构)。正确流程是:对目标UTF-8文本单独做gzip压缩→Base64编码→将编码结果嵌入JSON载荷后发送。

具体实现代码

1. 引入zlib库并实现gzip压缩函数

LoadRunner支持调用zlib库,注意使用deflateInit2时添加15+16参数生成标准gzip格式(而非zlib原生格式,这是多数人踩坑的点):

#include <zlib.h>
#include <string.h>

// 自定义gzip压缩函数
int gzip_compress(const char *input, int input_len, char *output, int *output_len) {
    z_stream zs;
    memset(&zs, 0, sizeof(zs));

    // 初始化gzip压缩(15+16表示生成gzip头/尾)
    if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
        lr_error_message("Gzip初始化失败");
        return -1;
    }

    zs.next_in = (Bytef *)input;
    zs.avail_in = input_len;
    zs.next_out = (Bytef *)output;
    zs.avail_out = *output_len;

    // 执行压缩直到完成
    int ret = deflate(&zs, Z_FINISH);
    if (ret != Z_STREAM_END) {
        deflateEnd(&zs);
        lr_error_message("Gzip压缩失败,错误码:%d", ret);
        return -1;
    }

    *output_len = zs.total_out;
    deflateEnd(&zs);
    return 0;
}

2. 压缩目标文本并转为Base64

Action() {
    // 待压缩的UTF-8文本
    char target_text[] = "需要压缩的UTF-8内容";
    int text_len = strlen(target_text);

    // 分配压缩缓冲区(建议设为原长度1.5倍+16,可根据实际调整)
    char compressed_buf[1024 * 5];
    int compressed_len = sizeof(compressed_buf);

    // 执行gzip压缩
    if (gzip_compress(target_text, text_len, compressed_buf, &compressed_len) != 0) {
        return -1;
    }

    // 将二进制压缩结果转为Base64编码
    web_convert_param("compressed_base64", 
                      "SourceEncoding=BINARY", 
                      "TargetEncoding=BASE64", 
                      "SourceString={compressed_buf}", 
                      "SourceLength=%d", compressed_len, 
                      LAST);

    // 构造包含编码后字段的JSON载荷
    char json_payload[1024 * 10];
    sprintf(json_payload, "{\"other_key\":\"明文值\",\"gzip_field\":\"%s\"}", lr_eval_string("{compressed_base64}"));

    // 发送请求(注意不要加ContentEncoding参数)
    web_custom_request("Submit_Compressed_JSON",
                       "URL=http://你的服务器地址",
                       "Method=POST",
                       "Body={json_payload}",
                       "ContentType=application/json;charset=UTF-8",
                       LAST);

    return 0;
}

关键注意事项

  • 避免误用ContentEncoding:该参数是告知服务器「整个请求体已gzip压缩」,会导致JSON结构被破坏,完全不符合你的需求。
  • zlib格式区分:deflateInit2的第三个参数必须加15+16,否则生成的是zlib格式压缩数据,而非标准gzip格式,无法匹配目标转换效果。
  • Base64编码处理二进制:必须指定SourceEncoding=BINARY和SourceLength,否则二进制数据中的\0会导致字符串截断,编码结果错误。

内容的提问来源于stack exchange,提问作者Lucky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:00:27