简体   繁体   中英

Distinguish between read and connection timeouts in HttpURLConnection

I want to distinguish between a connection timeout and a read timeout when using HttpURLConnection . It throws SocketTimeoutException when any of the two happen.

In case a connection timeout happens, a message is included as the exception message. Example:

failed to connect to /192.168.X.X (port X) after Xms

In case a read timeout happens, no message is included.

Relevant:

Of course I could distinguish them by the fact that one seems to include a message and the other does not, but doesn't seem sensible. If the implementation changes the code breaks.

I would have expected two different exceptions. Perhaps there's something I'm missing.

Once the timeout values are set using the setters, you can do the following

try {
  connection.connect();
  try {
    yourCustomReadMethodThatThrowsSocketTimeoutException(connection);
  } catch (SocketTimeoutException e) {
    Log.e("asdf", "this is a read timeout");
  }
} catch (SocketTimeoutException e) {
  Log.e("asdf", "this is a connect timeout");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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