is URL Connectable - Android Network

Android examples for Network:URL

Description

is URL Connectable

Demo Code


//package com.java2s;

import java.io.IOException;
import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import android.content.Context;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.util.Log;

public class Main {
    public static boolean isURLConnectable(Context context, String url) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) new URL(url)
                        .openConnection();
                urlc.setConnectTimeout(10 * 1000); // 10 s.
                urlc.connect();/*  ww  w  .  j  a v a2 s  .c o  m*/
                if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http
                    // connection is fine).
                    Log.wtf("Connection", "Success !");
                    return true;
                } else {
                    return false;
                }
            } catch (MalformedURLException e1) {
                return false;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
}

Related Tutorials