0

I think there should be a fancier way to do this with RxJava?.

The code is trying to verify if it can reach a host but the timeout from the urlConnection does not seem to work properly. So a timer in a different thread might be a solution, but I think it can be simplified either with RxJava or other ways?

public boolean canReachHost(String hostAddress) {
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(hostAddress);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setInstanceFollowRedirects(false);
        urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(CONNECTION_TIMEOUT);
        urlConnection.setUseCaches(false);
        new Thread(new InterruptThread(Thread.currentThread(), urlConnection)).start();
        urlConnection.getInputStream();
        return urlConnection.getResponseCode() == 200;
    } catch (IOException e) {
        return false;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

public class InterruptThread implements Runnable {
    Thread parent;
    URLConnection con;

    InterruptThread(Thread parent, URLConnection con) {
        this.parent = parent;
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(CONNECTION_TIMEOUT);
            ((HttpURLConnection) con).disconnect();
        } catch (InterruptedException e) {
            ((HttpURLConnection) con).disconnect();
        }
    }

}

This is for Android.

Banana
  • 2,435
  • 7
  • 34
  • 60
Kenenisa Bekele
  • 835
  • 13
  • 34
  • >"timeout from the urlConnection does not seem to work properly" Have you already filed a major bug with Android JDK guys? – M. Prokhorov Feb 15 '18 at 12:03
  • the explanation is here https://stackoverflow.com/questions/6829801/httpurlconnection-setconnecttimeout-has-no-effect/11790633#11790633 – Kenenisa Bekele Feb 15 '18 at 12:09
  • I see. In that case, converting to RxJava directly wouldn't be much help, because there are different types of timeouts, and RxJava can only fence the whole request and emit a timeout signal. Interrupting IO would be trickier with this, and certain types of timeouts (the one which measures delays between parts of chunked response) is out of the question for this kind of operation. – M. Prokhorov Feb 15 '18 at 15:10

0 Answers0