在REST Assured中,如何设置超时?

时间:2017-10-23 12:58:29

标签: java-8 httpclient rest-assured

我正在使用RestAssured 2.8.0 我正在尝试设置自己的超时(对于网关超时), 所以,如果我在X毫秒后没有得到响应,我想中止。

我试过了:

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);

}

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

我也尝试添加

.queryParam("SO_TIMEOUT", 10)

.queryParam("CONNECTION_MANAGER_TIMEOUT", 10)
似乎没什么用。 它不会中止我的查询

4 个答案:

答案 0 :(得分:15)

您可以通过设置HTTP客户端参数来配置超时:

{{1}}

答案 1 :(得分:3)

CoreConnectionPNames起已弃用,这是一种较新的方法。这适用于Apache HTTP客户端4.5.3:

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;

import io.restassured.RestAssured;
import io.restassured.config.HttpClientConfig;

...

RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setSocketTimeout(5000)
    .build();

HttpClientConfig httpClientFactory = HttpClientConfig.httpClientConfig()
    .httpClientFactory(() -> HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .build());

RestAssured.config = RestAssured
    .config()
    .httpClient(httpClientFactory);

答案 2 :(得分:0)

非常简单

doc = Jsoup.connect(company_url).timeout(2000).get();

company_url是您尝试点击的API URL。

答案 3 :(得分:0)

以下配置对我有用。

RestAssured.config=RestAssuredConfig.config()
                        .httpClient(HttpClientConfig.httpClientConfig()
                                .setParam("http.socket.timeout",1000)
                                .setParam("http.connection.timeout", 1000));