daydr3am3r
daydr3am3r

Reputation: 956

Kotlin - Check if URL is reachable

I have a small application that displays a webpage inside a WebView. When the user starts the app for the first time, he needs to enter the website data (URL, http/https, port, username and password) in a wizard-like activity. Before saving the data, I need to check if the URL is reachable.

I tried a few things I found here (most of them in Java) but so far I couldn't get this to work.

This was one of the approaches I found and while I find it a bit odd, I decided to give it a try but nothing happens.

val runtime = Runtime.getRuntime()
val proc = runtime.exec("ping www.google.com")

val mPingResult = proc.waitFor()
if (mPingResult == 0)
{
    isReachable = true
}

return isReachable!!

This returns false all the time, no specific error (even when checking on google.com).

return try
{
    InetAddress.getByName("https://www.google.com").isReachable(3000)
    true
}
catch (e: Exception) { false }

The last things I tried fail because they should be run on the main thread (I am actually trying to block the user from going forward until the server responds)

val url = URL("http://www.google.com")
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
val code: Int = connection.responseCode

if (code == 200) { isReachable = true }

return isReachable!!

val url = URL("http://www.google.com")
val urlc = url.openConnection() as HttpURLConnection
urlc.connectTimeout = 10 * 1000 // 10 s.
urlc.connect()
if (urlc.responseCode == 200)
{
    Log.wtf("Connection", "Success !")
    isReachable = true
}

return isReachable!!

HttpURLConnection.setFollowRedirects(false)
val httpURLConnection = (URL("https://www.google.com").openConnection() as HttpURLConnection)
httpURLConnection.requestMethod = "HEAD"
httpURLConnection.setRequestProperty(
    "User-Agent",
    "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"
)
return try { httpURLConnection.responseCode == HttpURLConnection.HTTP_OK }
catch (e: IOException) { false }
catch (e: UnknownHostException){ false }

Leaving aside the fact that I'm running these on main thread and I shouldn't, what am I doing wrong here? First time trying to do this in Kotlin / Android so I'm pretty sure it's something simple I'm missing.

Upvotes: 1

Views: 2035

Answers (1)

Mohit Ajwani
Mohit Ajwani

Reputation: 1338

You might be aware that we can't run network operations on the main thread as it will lead to ANR scenario. What you can do here is show a loader and start your network call on the IO Thread. Once you get the callback, dismiss the loader and redirect to the Webview with request to load the url.

Upvotes: 1

Related Questions