Java URL Exist existsURL(String url)

Here you can find the source of existsURL(String url)

Description

Check if the specified URL exists.

License

Open Source License

Parameter

Parameter Description
url the URL to check

Return

true if the URL exists

Declaration

public static boolean existsURL(String url) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.*;

public class Main {
    /**//w  w w .ja  va  2s. co m
     * Check if the specified URL exists.
     * @param url the URL to check
     * @return true if the URL exists
     */
    public static boolean existsURL(String url) {
        try {
            //HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection connection = (HttpURLConnection) new URL(url)
                    .openConnection();
            connection.setRequestMethod("HEAD");

            return (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection
                    .getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT);
        } catch (Exception e) {
            System.out.println("Error accessing: " + url);
            e.printStackTrace();
            return true; //Return true to move on!
        }
    }

    /**
     * Append a line to a file.
     * @param string the line to append to the file
     * @param filename the file to append to
     */
    public static void println(String string, String filename) {
        try {
            BufferedWriter outs = new BufferedWriter(new FileWriter(
                    filename, true));
            outs.write(string);
            outs.newLine();
            outs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

  1. exists(String url)
  2. exists(URL url)
  3. exists(URL url)
  4. exists(URL url)
  5. existsHttp(String URLName)
  6. existsURL_bak(String url)