0

In my android app I have a method that checks connection with server by url. It is working great, but only on devices with oreo and below. From android 9 getResponseCode() method from HttpUrlConnection always returns IOException. Logcat also shows a warn, to the line of code with urlc.connect();

W/System.err: at pl.wrestleone.goodwrestleone.MainActivity.isURLReachable(MainActivity.java:290)

How can I repair this strange method behavior? Thanks for any help.

static public boolean isURLReachable(Context context, String webUrl) {

    ConnectivityManager cm;
    cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL(webUrl);   // Change to "http://google.com" for www  test.
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(10 * 1000);          // 10 s.
            urlc.connect();
            if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                return true;

            } else {
                return false;
            }
        } catch (MalformedURLException e1) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}
tomerpacific
  • 4,704
  • 13
  • 34
  • 52

0 Answers0