java - RESTAssured 禁用 URL 编码无法正常工作
问题描述
我正在使用如下 URL 测试 HTTP Post 请求:
https://myurl.com/api/logs/%2Fvar%2Flog%2Fmessages?Api-Token=12332429nmdsafs
我禁用了 URL 编码,这里是我的发布请求:
RestAssured.given()
.contentType(JSON)
.log()
.all()
.urlEncodingEnabled(false)
.baseUri(RestAssured.baseURI)
.basePath(url)
.pathParam(LOG_PATH_PARAM_NAME, urlEncodeString(requireNonNull(logPath)))
.body(myJsonBody)
.when()
.post("/logs/{logPath}")
.then()
.statusCode(OK.getStatusCode());
我也试过这样:
RestAssured.given()
.contentType(JSON)
.log()
.all()
.urlEncodingEnabled(false)
.baseUri(RestAssured.baseURI)
.basePath(url)
.body(myJsonBody)
.when()
.post("/logs/" + urlEncodeString(requireNonNull(logPath)))
.then()
.statusCode(OK.getStatusCode());
这里是 urlEncodeString 方法:
private static String urlEncodeString(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
}
现在的问题是我上面提到的 URL 被编码为以下内容:
https://myurl.com/api/logs/var/log/messages?Api-Token=12332429nmdsafs
有谁知道这里有什么问题?或者知道解决方法?我已经尝试过双重逃脱路径。
编辑:
我刚刚发现禁用 URL 编码仅适用于 URL 参数。
解决方案
尽管您是正确的,given().urlEncodingEnabled(isEnabled).spec()...
只会禁用 URL 参数的编码,但您也可以使用 URL 本身对 URL 执行相同的操作
RequestSpecification mySpec = new RequestSpecBuilder().setUrlEncodingEnabled(false)
例如,如果我想在不编码的情况下向这个(确切的)URL 发出 get 请求http://api.cheapbooks.com/mathbooks/location/$amazonbooks%2Fscience%2Fmath
RestAssured 的默认行为会将 URL 双重编码为:http://api.cheapbooks.com/mathbooks/location/%24amazonbook%252Fscience%2Fmath
但是,如果您像mySpec
上面一样创建一个 RequestSpecification setUrlEncodingEnabled(false)
,您可以通过以下方式在哪里发出 http 请求:
given().spec(mySpec)...
或者
spec.setBaseUri(...)
您应该以这种方式获得所需的结果
推荐阅读
- java - 如何修复错误创建名为“sessionFactory”的bean错误?
- angular - PrimeNG 角度数据表加载字符串数组
- linux - 根据文本文件内容中的行数运行循环次数(Unix Shell Scripting)
- python - Celery link_error 引发 NotRegistered 异常
- asp.net-core - 如何从 Identity Server 4 端点获取路由数据
- apache-spark - 检索列中具有不同值的 Spark 数据集
- python - 在嵌套的 for 循环中使用 try-excepts
- google-cloud-platform - 导入到 SQL Mysql 实例
- c# - 我的子弹在第一次射击后不会移动,为什么?
- python - python -m 在公司代理后面