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

WireMock如何提取URL路径中等号后参数值并返回至响应体

问题原因

你当前通过{{request.path.[3]}}获取到的是路径第4个分段的完整字符串query2=id1,WireMock默认不会自动拆分等号后的内容,所以需要额外做参数提取或者调整匹配规则。

解决方案

方案1:直接对路径分段做正则提取(无需修改请求匹配规则)

仅修改响应体yourId的取值逻辑,用响应模板内置的regexExtract函数提取等号后的值即可:

{
    "name": "Req_GET",
    "request": {
        "urlPathPattern": "/manage/classids/query1=([a-zA-Z0-9]*)/query2=([a-zA-Z0-9]*)",
        "method": "GET"
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "yourId": "{{regexExtract request.path.[3] '=([a-zA-Z0-9]+)$' 1}}"
        },
        "transformers": [
            "response-template"
        ],
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

方案2:直接读取路径正则的捕获组(更高效)

你已经在urlPathPattern里写了正则捕获组,第二个捕获组就是你需要的id1值,直接读取匹配结果的捕获组即可:

{
    "name": "Req_GET",
    "request": {
        "urlPathPattern": "/manage/classids/query1=([a-zA-Z0-9]*)/query2=([a-zA-Z0-9]*)",
        "method": "GET"
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "yourId": "{{request.pathMatchResult.groups.2}}"
        },
        "transformers": [
            "response-template"
        ],
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

注:捕获组下标从1开始,groups.1对应query1的值ns1,groups.2对应query2的值id1

方案3:使用路径模板命名参数(可读性最高)

改用WireMock支持的URI路径模板,给参数命名后直接读取,后续维护更清晰:

{
    "name": "Req_GET",
    "request": {
        "urlPathTemplate": "/manage/classids/query1={query1Val}/query2={query2Val}",
        "method": "GET"
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "yourId": "{{request.pathParameters.query2Val}}"
        },
        "transformers": [
            "response-template"
        ],
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:54:04