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.


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

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


You can call him with

try {
    String parameters = ""; //
    URL url = new URL("" + parameters);
catch(Exception e){


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...




Use this. This works great for me :)

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("");
    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);
        Log.e("checking", "Checking network connection...");
        Log.e("checking", "Connection OK");
    catch(ClientProtocolException e){
    catch(IOException e){

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




All Articles