How to Check If Url Is Valid in Android

how to validate a URL / website name in EditText in Android?

Short answer

Use WEB_URL pattern in Patterns Class

 Patterns.WEB_URL.matcher(potentialUrl).matches()

It will return True if URL is valid and false if URL is invalid.

Long answer

As of Android API level 8 there is a WEB_URL pattern. Quoting the source, it "match[es] most part of RFC 3987". If you target a lower API level you could simply copy the pattern from the source and include it in your application. I assume you know how to use patterns and matchers, so I'm not going into more details here.

Also the class URLUtil provides some useful methods, e.g:

  • isHttpUrl()
  • isValidUrl()

The descriptions of the methods are not very elaborate, therefore you are probably best of looking at the source and figuring out which one fits your purpose best.

As for when to trigger the validation check, there are multiple possibilities: you could use the EditText callback functions

  • onFocusChanged(), or
  • onTextChanged()

or use a TextWatcher, which I think would be better.

DON'T USE URLUtil to validate the URL as below.

 URLUtil.isValidUrl(url)

because it gives strings like "http://" as valid URL which isn't true

How to check a specific URL is valid or not in Android?

Your almost there!

private class MyTask extends AsyncTask<Void, Void, Boolean> {
private URL mUrl;

public MyTask(URL url) {
mUrl = url;
}

@Override
protected Boolean doInBackground(Void... params) {
try {
HttpURLConnection urlc = (HttpURLConnection) mUrl.openConnection();
urlc.setConnectTimeout(10 * 1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1){
return false;
} catch (IOException e) {
return false;
}
}
}

When you need to check for the respons:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
URL url = new URL("http://www.google.com");
MyTask task = new MyTask(url){
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// Do your work here
}
}
};
task.execute();
}
}

Check if URL is valid in Android without catching Exception?

This solution does catch exceptions, however others may find it useful and doesn't require any libraries.

public boolean URLIsReachable(String urlString)
{
try
{
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
responseCode = urlConnection.getResponseCode();
urlConnection.disconnect();
return responseCode != 200;
} catch (MalformedURLException e)
{
e.printStackTrace();
return false;
} catch (IOException e)
{
e.printStackTrace();
return false;
}
}

Check if URL exists or not on Server

You will get Network On Main Thread Exception

Look at NetworkOnMainThreadException

so your method always returns false because of:

   catch (Exception e) {
e.printStackTrace();
return false;
}

quick fix:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

MyTask task = new MyTask();
task.execute(customURL);
}

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

@Override
protected void onPreExecute() {

}

@Override
protected Boolean doInBackground(String... params) {

try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}

@Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
}
}

With a ScheduledThreadPoolExecutor:

but remember to shut down it!!

public class MainActivity extends Activity {
String customURL;
String msg = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {

try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(customURL).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());

if(con.getResponseCode() == HttpURLConnection.HTTP_OK){

msg = "File exist!";

}else{

msg = "File does not exist!";

}

runOnUiThread(new Runnable() {

@Override
public void run() {

Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
return;
}

}
}, 0,10000, TimeUnit.MILLISECONDS);
}


Related Topics



Leave a reply



Submit