Java 如何使用 Jersey 2.x 设置连接和读取超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19543209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:13:56  来源:igfitidea点击:

How to set the connection and read timeout with Jersey 2.x?

javajersey

提问by David Michael Gang

In jersey 1 we had a function setConnectTimeoutin the class com.sun.jersey.api.client.Client.

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

In jersey 2 the javax.ws.rs.client.Clientclass is used where this function is missing.

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

How to set connection timeout and read timeout in jersey 2.x?

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

采纳答案by Lars

The code below works for me in Jersey 2.3.1 (inspiration found here: https://stackoverflow.com/a/19541931/1617124)

下面的代码在 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();
    }
}

回答by Siggen

You may also specify a timeout per request :

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

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