0

I want to check whether the url "https://www.example.com:8443" is reachable or not in android studio in java with the socket creation at client side.

supriya
  • 11
  • 1
  • 4

1 Answers1

0

First you must add the following to your Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

For Network-Operations you must use a async task for this. It's not allowed to call a Network-Operation on GUI-Thread. See here

new PingTask().execute("10.0.0.2", "8080");

Then create a Async-Task for the ping execution:

private class PingTask extends AsyncTask<String, Void, Boolean> {

    protected Boolean doInBackground(String... params) {
        String url = params[0];
        int port =  Integer.parseInt(params[1]);
        boolean success = false;

        try {
            success = pingURL(url, port);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return success;
    }

    protected void onPostExecute(Boolean result) {
        // do something when a result comes from the async task.
    }
}

public static boolean pingURL(String hostname, int port) throws UnknownHostException, IOException {
    boolean reachable = false;

    try (Socket socket = new Socket(hostname, port)) {
      reachable = true;
    }

    return reachable;
}
Flagman
  • 416
  • 6
  • 24
  • I have tried this code before in eclipseIDE, and it works perfectly fine. But when I try it on Android Studio, exception occurs. – supriya Sep 08 '15 at 04:42
  • I've edited my solution. It works perfect in my sample app with AndroidStudio – Flagman Sep 08 '15 at 09:30