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?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1.
The read timeout is applied to both the TCP socket and for individual read IO operations including on Source of the Response. The default value is 10 seconds.
From the client side, the “read timed out” error happens if the server is taking longer to respond and send information. This could be due to a slow internet connection, or the host could be offline. From the server side, it happens when the server takes a long time to read data compared to the preset timeout.
request timeout — a time period required to process an HTTP call: from sending a request to receiving a response. connection timeout — a time period in which a client should establish a connection with a server. socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.
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(); } }
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With