I am testing a HTTP Post request with an URL like following:
https://myurl.com/api/logs/%2Fvar%2Flog%2Fmessages?Api-Token=12332429nmdsafs
I have URL encoding disabled and here my post request:
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());
I also tried it like this:
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());
And here the urlEncodeString method:
private static String urlEncodeString(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
}
The problem now is that my URL mentioned above gets encoded to following:
https://myurl.com/api/logs/var/log/messages?Api-Token=12332429nmdsafs
Does anyone know what is wrong here? Or knows a workaround? I already tried to double escape the path.
EDIT:
I just found out that disabling URL encoding only works for the URL parameters.
Although you are correct that given().urlEncodingEnabled(isEnabled).spec()...
will only disable encoding for URL parameters, you can also do the same for the URL itself using
RequestSpecification mySpec = new RequestSpecBuilder().setUrlEncodingEnabled(false)
For example, if I want to make a get request to this (exact) URL without encoding it http://api.cheapbooks.com/mathbooks/location/$amazonbooks%2Fscience%2Fmath
The default behavior of RestAssured will double encode the URL to this: http://api.cheapbooks.com/mathbooks/location/%24amazonbook%252Fscience%2Fmath
But if you create a RequestSpecification like the mySpec
above, where setUrlEncodingEnabled(false)
and you make a http request by either doing :
given().spec(mySpec)...
or
spec.setBaseUri(...)
You should get the desired result this way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With