257. Setting a timeout

By default, a request has no timeout (infinite timeout). To set the amount of time we want to wait for a response (timeout), we can call the HttpRequest.Builder.timeout() method. This method gets an argument of the Duration type, which can be used like so:

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.timeout(Duration.of(5, ChronoUnit.MILLIS))
.build();

If the specified timeout elapses, then java.net.http.HttpConnectTimeoutException will be thrown.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset