55

在球衣 1 中,我们在类中有一个函数setConnectTimeoutcom.sun.jersey.api.client.Client

在球衣 2 中,javax.ws.rs.client.Client该类用于缺少此功能的地方。

如何在 jersey 2.x 中设置连接超时和读取超时?

4

3 回答 3

76

下面的代码在 Jersey 2.3.1 中适用于我(灵感在这里找到:https ://stackoverflow.com/a/19541931/1617124 )

public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
    client.property(ClientProperties.READ_TIMEOUT,    1000);

    WebTarget target = client.target("http://1.2.3.4:8080");

    try {
        String responseMsg = target.path("application.wadl").request().get(String.class);
        System.out.println("responseMsg: " + responseMsg);
    } catch (ProcessingException pe) {
        pe.printStackTrace();
    }
}
于 2013-10-24T09:17:36.430 回答
39

您还可以为每个请求指定超时:

public static void main(String[] args) {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://1.2.3.4:8080");

    // default timeout value for all requests
    client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
    client.property(ClientProperties.READ_TIMEOUT,    1000);

    try {
        Invocation.Builder request = target.request();

        // overriden timeout value for this request
        request.property(ClientProperties.CONNECT_TIMEOUT, 500);
        request.property(ClientProperties.READ_TIMEOUT, 500);

        String responseMsg = request.get(String.class);
        System.out.println("responseMsg: " + responseMsg);
    } catch (ProcessingException pe) {
        pe.printStackTrace();
    }
}
于 2016-03-17T09:28:56.380 回答
1

从 jersey 2.26(使用JAX-RS 2.1)开始,有新的方法:

ClientBuilder builder = ClientBuilder.newBuilder()
        .connectTimeout(5000, TimeUnit.MILLISECONDS)
        .readTimeout(5000, TimeUnit.MILLISECONDS);
        //some more calls if necesary, e.g.
        //.register(LoggingFilter.class);
            
        Client restClient = builder.build();
于 2020-08-21T09:39:58.667 回答