问与答 java-如何设置连接并使用Jersey 2.x读取超时?

tyler · 2020-02-22 07:46:44 · 热度: 62

在球衣1中,我们在类javax.ws.rs.client.Client中具有函数setConnectTimeout。

在运动衫2中,缺少此功能的位置为javax.ws.rs.client.Client类。

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

猜你喜欢:
共收到 2 条回复
sidney #1 · 2020-02-22 07:46:45

下面的代码在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();
    }
}
thobian #2 · 2020-02-22 07:46:46

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

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();
    }
}
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册