How to set the timeout of request sended by ClientResource in Restlet Framework

643 Views Asked by At

I'm using the Restlet framework and specifically the class ClientResource to send HTTP request to a server through its own get(), post(), put() and delete() methods. Since sometimes the server is offline and therefore unreachable, I would like to set a smaller timeout than the default. How can I do it?

At the moment I've tried in this way with no success:

ClientResource cr = new ClientResource(uri);

Context context = new Context();
context.getParameters().add("maxIoIdleTimeMs", "0");
context.getParameters().add("ioMaxIdleTimeMs", "0");
context.getParameters().add("socketTimeout", "1000");

cr.setNext(new Client(context, Protocol.HTTP));
cr.setRetryOnError(false);

...

Representation r = cr.get();

The result is the same of the default case, that is a timeout of about 60-90 seconds before the connection error exception is returned from the get() method. My purpose is to anticipate it.

1

There are 1 best solutions below

0
On

To set the timeout properly:

Component c = new Component();
Client client = c.getClients().add(Protocol.HTTP);
client.getContext().getParameters().add ( "socketTimeout", "10" );
Response resp = client.handle(new Request(Method.GET, "https://swapi.co/api/people/1/"));
System.out.println("Output: " + resp.getEntity().getText());

This code will throw a timeout exception as what you needed, increase the socketTimeout to at least 1000 to be able to retrieve the test API JSON response.

Also, these versions was used:

<dependency>
  <groupId>org.restlet.jse</groupId>
  <artifactId>org.restlet</artifactId>
  <version>2.4.0</version>
</dependency>
<dependency>
  <groupId>org.restlet.jse</groupId>
  <artifactId>org.restlet.ext.httpclient</artifactId>
  <version>2.4.0</version>
</dependency>