UrlConnection with Timer转换为RxJava

时间:2018-02-15 11:50:23

标签: java android multithreading rx-java httpurlconnection

我认为使用RxJava应该有更好的方法吗?

代码正在尝试验证它是否可以到达主机,但urlConnection的超时似乎无法正常工作。所以不同线程中的计时器可能是一个解决方案,但我认为可以用RxJava或其他方式简化它?

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();
        }
    }

}

这适用于Android。

0 个答案:

没有答案