Scripts: Scripts: Java :: using java.net tools :: Library Article #2

Developer's Section

Check if a webpage exists in Java
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating: 
Average Votes: (1839)
Rate It:   
Favorites:

learn how to check if a webpage exists in Java.

In this script we will be using the java.net package to figure out if certain webpage exists on the internet. The method exists() first makes sure no redirects are executed. Then it creates an object of type HttpURLConnection to determine if the webpage exists. Finally, it compares the value of getResponseCode() with the static value of HttpURLConnection.HTTP_OK.


Example:

 Code Snippet 1

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

public class testClass {

  public static void main(String args[]) {
  
  String u = "http://www.abcdefg.com";
  
  //test if http://www.abcdefg.com exists
  boolean answer = exists(u);
   
  if(answer == true){
      System.out.println("the website:" + u + " exists");
  }
  else {
      System.out.println("the website:" + u + " doesn't exist");
  }
  
  }

  public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {       
       return false;
    }
  }
}



See other Scripts in using java.net tools

 

Submit Your Scripts:

If you would like to have your Java scripts published in this section please fill out
the form below:
*Your Name or
Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]
  

 


© 2018 Erobo Software, Inc. All Rights Reserved. | Read Privacy Notice | RSS