Search This Blog

Breaking

Tuesday, 5 December 2023

December 05, 2023

[Rest Assured][Fix] Getting API Response from Postman, but when same request hit from Rest assured code, API does not respond

 Recently, I was debugging an issue for a team mate for which API was not responding when ran through java code. The same API was responding from the same code from my machine, from his postman, from any other machines, but just not responding when he was running from the java code.


Below was the request which code were making:



RestAssured.baseURI = “URL”;

RestAssured.useRelaxedHTTPSValidation();


Response response = RestAssured.given()

                                          .auth()

                                          .preemptive()

                                          .basic(username, password)

                                          .header("Content-Type", "application\json")

                                          .body(requestBody)

                                          .post(endPoint)

                                          .then().extract().response();

                                          .


When we were hitting this code, It was not returning any response and the code was in execution mode. We tried to debug it also, but we could not get much information.


Fix

After an hour debug, we tried to play with the config settings. We got to know after reading the doc, 

that by default REST Assured adds the charset header automatically. 

To disable this completely we can configure the EncoderConfig like this:


 given()

.config(RestAssured.config()

.encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)));


With the EncoderConfig we can specify the default content encoding charset (if it's not specified in the content-type header) and query parameter charset for all requests. If no content charset is specified then ISO-8859-1 is used and if no query parameter charset is specified then UTF-8 is used. Usage example:


RestAssured.config = RestAssured.config().encoderConfig(encoderConfig().defaultContentCharset("US-ASCII"));


This solved our issue when we started getting the response.


The other notable thing was, when we removed it later, we were started getting the response too. Though we didn't check the server logs, however, it seems that the other responses were coming from cache.