1

Need to make a program that takes a valid URL of a webpage like www.stackoverflow.com/questions and its IP address equivalent. The program will then find that webpage and return the status code of the page to us such as 200 OK and 404 NOT FOUND. If the webpage isn’t reachable, a message should be returned explaining the situation.

Here’s what I have done so far:

interface Result {
  public boolean ok ();
  public String message (); }

class Page {
  public Result check ( String wholeURL ) throws Exception {
     throw new Exception ( "Not sure about the rest”); } }

Also if I were to check a page like http://www.stackoverflow.com I’ll create an instance of Page and then do something like this:

Page page = new PageImplementation ();
Result result = page.check ( "http://www.stackoverflow.com:60" );
if ( result.ok () ) { ... }
else { ... }

The object that is returned is an instance of Result, and the “ok” method should return true when the status code is 200 OK but false otherwise. The method “msg” should return the status code as string.

Ajay Punja
  • 101
  • 3
  • 11

2 Answers2

2

Have a look at the HttpURLConnection class within the JDK or use Apache Http Components.

Basically you try to connect to the url and check the response header or wait for a timeout if the server isn't reachable at all.

With HttpURLConnection it might look like this:

URL url = new URL("http://www.stackoverflow.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();

int httpStatusCode = connection.getResponseCode(); //200, 404 etc.
Thomas
  • 80,843
  • 12
  • 111
  • 143
  • I tried this approach, however I want to be able to enter the URL with or without the "http://", is this possible? – Ajay Punja Mar 06 '13 at 16:58
  • Can't you check for it in your code and prepend it if necessary? – laz Mar 06 '13 at 18:46
  • How can I prepend it? I found a way in python import called httplib but unfortunately that only works for Python. Is there a similar import for Java? I want a way to check status of code with or without the need of "http://" at the beginning. – Ajay Punja Mar 06 '13 at 21:07
  • 1
    Well, the url is a string, so check if the string starts with `http://` and if not, prepend it. It's plain string manipulation before creating the `URL` object. – Thomas Mar 07 '13 at 08:49
  • Thanks. Your sentence jogged my memory and found a key word in there to help. =) – Ajay Punja Mar 07 '13 at 09:17
1

You can use some api like commons http ,

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

..........


public Result check ( String fullURL ) throws Exception {

  HttpClient client = new HttpClient();
  GetMethod method = new GetMethod(url);

  int statusCode = client.executeMethod(method);

   //Update your result object based on statuscode
}
Avinash Singh
  • 2,564
  • 1
  • 14
  • 20