0

According to this answer, the method HttpURLConnection.setReadTimeout() allows you to set the max amount of time to wait for server to START reading data from input stream - as stated by Oracle:

A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

It does not allow you to set timeout to force server to FINISH reading data within a specific amount of time

My question is:

Is there a way to set a timeout to force server to finish reading data within a specified amount of time or is this at all not possible?

Thanks

S.O.S
  • 848
  • 10
  • 30

1 Answers1

0

You cannot set a timeout, as per your requirement, on a HttpURLConnection.
However you could mitigate the situation using a separate Thread.

Get an ExecutoreService

final ExecutorService executor = Executors.newSingleThreadExecutor();

Submit your Callable<T> task, where T is the data type you'll return after reading from the HttpURLConnection data stream.

final Future<T> result = executor.submit(new HttpTask());

You'll get a Future<T>, which represent the outcome of your task.
Now, use the Future#get(long timeout, TimeUnit unit) method.

try {
   final T value = result.get(10, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
   result.cancel(true);
}

In that case, If more than 10 seconds passes, a TimeoutException will be thrown and you'll be able to abruptly end your task.

LppEdd
  • 20,274
  • 11
  • 84
  • 139
  • I'm already using ExecutorService in my application. However, calling result.cancel(true); will NOT terminate the underlying connection/thread. I'm trying to close/terminate connection in the underlying thread precisely for this reason when connection is ongoing for too long. So this would not address my problem. – S.O.S Feb 19 '19 at 19:43
  • @S.O.S you may want to handle an InterruptedException and close the connection accordingly. – LppEdd Feb 19 '19 at 19:45
  • @S.O.S and by the way, you can pass an HttpURLConnection as constructor parameter to your Callable task, and close it inside the catch block if necessary. – LppEdd Feb 19 '19 at 19:50