首页 > 解决方案 > 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 参数。

标签: javaurlurl-encodingrest-assured

解决方案


尽管您是正确的,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(...)

您应该以这种方式获得所需的结果


推荐阅读