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

JavaJersey

Java Problem Overview


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

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

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

Java Solutions


Solution 1 - Java

The code below works for me in Jersey 2.3.1 (inspiration found here: 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();
    }
}

Solution 2 - Java

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

Solution 3 - Java

Starting from jersey 2.26 (which uses JAX-RS 2.1) there are new methods for that:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid Michael GangView Question on Stackoverflow
Solution 1 - JavaLarsView Answer on Stackoverflow
Solution 2 - JavaSiggenView Answer on Stackoverflow
Solution 3 - JavaLonzakView Answer on Stackoverflow