Search code examples
java-8httpclientrest-assured

In REST Assured, how do I set a timeout?


I'm using RestAssured 2.8.0 and I'm trying to set my own timeout (for gateway timeout), so if I don't get response after X milliseconds I want to abort.

I tried:

public static ValidatableResponse postWithConnectionConfig(String url, String body, RequestSpecification requestSpecification, ResponseSpecification responseSpecification) {
    ConnectionConfig.CloseIdleConnectionConfig closeIdleConnectionConfig = new ConnectionConfig.CloseIdleConnectionConfig(1L, TimeUnit.MILLISECONDS);
    ConnectionConfig connectionConfig = new ConnectionConfig(closeIdleConnectionConfig);
    RestAssuredConfig restAssuredConfig = new RestAssuredConfig().connectionConfig(connectionConfig);


    return given().specification(requestSpecification)
            .body(body)
            .config(restAssuredConfig)
            .post(url)
            .then()
            .specification(responseSpecification);

}

or

ConnectionConfig connectionConfig = new ConnectionConfig()
            .closeIdleConnectionsAfterEachResponseAfter(10L, TimeUnit.MILLISECONDS);
RestAssuredConfig restAssuredConfig = new RestAssuredConfig().connectionConfig(connectionConfig);

I also tried to add

.queryParam("SO_TIMEOUT", 10)

or

.queryParam("CONNECTION_MANAGER_TIMEOUT", 10)

nothing seem to work. It doesn't abort my query


Solution

  • You can configure timeouts by setting HTTP client parameters:

    RestAssuredConfig config = RestAssured.config()
            .httpClient(HttpClientConfig.httpClientConfig()
                    .setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)
                    .setParam(CoreConnectionPNames.SO_TIMEOUT, 1000));
    
    given().config(config).post("http://localhost:8884");