How to ping a site from an Android activity and get a response?

I used isReachable but it didn't work and I used ConnectivityManager and getNetworkInfo; it actually only works for checking if I am connected to the internet ...

But the problem is I want to check if I can access the internet, so I want to ping the site to see if there is an answer.

+3


source to share


2 answers


For get method:

private void executeReq(URL urlObject) throws IOException{
    HttpURLConnection conn = null;

    conn = (HttpURLConnection) urlObject.openConnection();
    conn.setReadTimeout(100000); //Milliseconds
    conn.setConnectTimeout(150000); //Milliseconds
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    // Start connect
    conn.connect();
    String response = convertStreamToString(conn.getInputStream());
    Log.d("Response:", response);
}

      

You can call him with



try {
    String parameters = ""; //
    URL url = new URL("http://alefon.com" + parameters);
    executeReq(url);
}
catch(Exception e){
    //Error
}

      

To test your internet connection use:

private void checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (null == ni)
        Toast.makeText(this, "no internet connection", Toast.LENGTH_LONG).show();
    else {
         Toast.makeText(this, "Internet Connect is detected .. check access to sire", Toast.LENGTH_LONG).show();
         //Use the code above...
    }
}

      

+5


source


Use this. This works great for me :)



public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.e("checking", "Checking network connection...");
        httpClient.execute(httpGet);
        Log.e("checking", "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.e("checking", "Connection unavailable");
}

      

+3


source







All Articles