简体   繁体   English

如何在 Restlet Framework 中设置 ClientResource 发送请求的超时时间

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

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.我正在使用 Restlet 框架,特别是 class ClientResource通过它自己的get()post()put()delete()方法向服务器发送 HTTP 请求。 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.结果与默认情况相同,即在从get()方法返回连接错误异常之前大约超时 60-90 秒。 My purpose is to anticipate it.我的目的是预测它。

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.此代码将根据您的需要抛出超时异常,将socketTimeout增加到至少 1000 以便能够检索测试 API JSON 响应。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM