Rest Assured中含逗号的路径参数传递异常问题求助
解决Rest Assured路径参数逗号自动转义的问题
Rest Assured默认会对路径参数做URL编码,导致逗号被转义成%2C。如果后端服务要求路径中保留原始逗号,可以通过以下两种方式解决:
方法一:直接拼接路径(绕过pathParam编码)
放弃使用pathParam方法,直接将参数拼接到请求URL模板中,彻底避免自动编码逻辑。
示例代码:
// 获取原始CalendarId参数 String calendarId = testCaseBean.getCalendarId().toString(); // 替换URL模板中的占位符,生成完整请求路径 String fullRequestUrl = EndPoint.GET_CALENDAR_BUSINESS_DAY_INFO_DATE_PARAM.replace("{CalendarId}", calendarId); ValidatableResponse response = given() .header("Authorization", token) .header("Content-type", "application/json") .queryParam("from", testCaseBean.getStartDate()) .queryParam("to", testCaseBean.getEndDate()) .queryParam("monthEnd", testCaseBean.getMonthEndBusinessDay()) .when().log().all() .get(fullRequestUrl) .then().log().all();
方法二:配置自定义URL编码策略
通过UrlEncoderConfig将逗号标记为安全字符,让Rest Assured不对其进行编码,同时保留pathParam的使用规范。
示例代码:
ValidatableResponse response = given() .header("Authorization", token) .header("Content-type", "application/json") // 启用URL编码并指定逗号为安全字符 .urlEncodingEnabled(true) .urlEncoderConfig(new UrlEncoderConfig().addSafeCharacter(',')) .pathParam("CalendarId", testCaseBean.getCalendarId().toString()) .queryParam("from", testCaseBean.getStartDate()) .queryParam("to", testCaseBean.getEndDate()) .queryParam("monthEnd", testCaseBean.getMonthEndBusinessDay()) .when().log().all() .get(EndPoint.GET_CALENDAR_BUSINESS_DAY_INFO_DATE_PARAM) .then().log().all();
说明:第二种方法更贴合Rest Assured的编码设计,适合需要保持参数化写法的场景;第一种方法简单直接,适合快速修复问题。
内容的提问来源于stack exchange,提问作者Pratik
相关产品推荐
相关产品推荐

