[英]How to set the timeout of request sended by ClientResource in Restlet Framework
我正在使用 Restlet 框架,特別是 class ClientResource
通過它自己的get()
、 post()
、 put()
和delete()
方法向服務器發送 HTTP 請求。 由於有時服務器處於脫機狀態,因此無法訪問,因此我想設置比默認值更小的超時。 我該怎么做?
目前我已經嘗試過這種方式但沒有成功:
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();
結果與默認情況相同,即在從get()
方法返回連接錯誤異常之前大約超時 60-90 秒。 我的目的是預測它。
正確設置超時:
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());
此代碼將根據您的需要拋出超時異常,將socketTimeout
增加到至少 1000 以便能夠檢索測試 API JSON 響應。
此外,還使用了這些版本:
<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.