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.

0

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this approach, however I want to be able to enter the URL with or without the "http://", is this possible?
Can't you check for it in your code and prepend it if necessary?
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.
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.
Thanks. Your sentence jogged my memory and found a key word in there to help. =)
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.