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.