Documente Academic
Documente Profesional
Documente Cultură
if (args.length == 0) {
System.err.println(
"Please provide a URL to check");
} else {
HttpURLConnection.setFollowRedirects(false);
String urlString = args[0];
try {
URL url = new URL(urlString);
URLConnection connection =
url.openConnection();
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection =
(HttpURLConnection)connection;
httpConnection.connect();
int response =
httpConnection.getResponseCode();
System.out.println("Response: " + response);
String location =
httpConnection.getHeaderField("Location");
if (location != null) {
System.out.println(
"Location: " + location);
}
InputStream is =
httpConnection.getInputStream();
byte[] buffer = new byte [256];
while (is.read (buffer) != -1) {}
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now, when you run the application with a URL of
http://java.sun.com/jdc/:
java SimpleURLCheck http://java.sun.com/jdc/
it should produce the following results:
Response: 301
Location: http://developer.java.sun.com/developer/
The check even works for https URLs (the following command
should be entered on one line):
java SimpleURLCheck
https://www.madonotcall.govconnect.com/
should produce the following results:
Response: 302
Location: cookiestest.asp
Remember to add proxy settings if you're behind a firewall, that
is, for https.proxyHost and https.proxyPort.
1xx
2xx
3xx
4xx
5xx
informational
successful
redirection
error
server error
java.io.*;
java.net.*;
javax.swing.text.*;
javax.swing.text.html.*;
class EnhancedURLCheck {
public static void main(String[] args) {
HttpURLConnection.setFollowRedirects(false);
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet
// handle charset's properly.
doc.putProperty("IgnoreCharsetDirective",
Boolean.TRUE);
try {
// Create a reader on the HTML content.
Reader rd = getReader(args[0]);
// Parse the HTML.
kit.read(rd, doc, 0);
// Iterate through the elements
// of the HTML document.
ElementIterator it = new ElementIterator(doc);
javax.swing.text.Element elem;
while ((elem = it.next()) != null) {
SimpleAttributeSet s = (SimpleAttributeSet)
elem.getAttributes().getAttribute(
HTML.Tag.A);
if (s != null) {
validateHref(
(String)s.getAttribute(
HTML.Attribute.HREF));
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(1);
}
// Returns a reader on the HTML data. If 'uri' begins
// with "http:", it's treated as a URL; otherwise,
// it's assumed to be a local filename.
static Reader getReader(String uri)
throws IOException {
if (uri.startsWith("http:")) {
// Retrieve from Internet.
URLConnection conn =
new URL(uri).openConnection();
return new
InputStreamReader(conn.getInputStream());
} else {
// Retrieve from file.
return new FileReader(uri);
}
}
private static void validateHref(String urlString) {
if ((urlString != null) &&
urlString.startsWith("http://")) {
try {
URL url = new URL(urlString);
URLConnection connection =
url.openConnection();
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection =
(HttpURLConnection)connection;
httpConnection.setRequestMethod("HEAD");
httpConnection.connect();
int response =
httpConnection.getResponseCode();
System.out.println("[" + response + "]" +
urlString);
String location =
httpConnection.getHeaderField("Location");
if (location != null) {
System.out.println(
"Location: " + location);
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you run the report on the http://java.sun page:
java EnhancedURLCheck http://java.sun.com
it should produce output similar to the following (only the first
few lines of the output are shown):
[200]http://java.sun.com/
[200]http://search.java.sun.com/search/java/
advanced.jsp
[200]http://java.sun.com/
[302]http://servlet.java.sun.com/logRedirect/
frontpage-nav/http://java.sun.com/products/
Location: http://java.sun.com/products/
[302]http://servlet.java.sun.com/logRedirect/
frontpage-nav/http://java.sun.com/j2ee/Location:
http://java.sun.com/j2ee/
For more information about using URLs, see the lesson "Working
with URLs" in the Java Tutorial
(http://java.sun.com/docs/books/tutorial/networking/urls/index.html).
Also see the lesson "Reading from and Writing to a URLConnection"
(http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - REUSING EXCEPTIONS
When an exceptional condition occurs in a program, it's typical
to throw an exception. The syntax for throwing an exception often
looks something like this:
throw new MyException("String");
Literally, you create the exception when the exceptional
condition happens, and immediately throw it to the caller (or to
some enclosing try-catch block).
If you print a stack trace at that point with printStackTrace(),
the information you see is filled with the details of the stack
at the time the exception was created. This might sound obvious.
However, if you want to avoid creating new objects when an
exception occurs, you can create the exception once, and reuse it
when the exceptional condition reoccurs. A common design pattern
for this is called a Singleton. You can create the object the
first time you need it, and then keep reusing the same object.
For example:
MyObject myObject = null;
private synchronized MyObject getMyObject() {
if (myObject == null) {
myObject = new MyObject();
}
return myObject;
}
What happens if you use a pattern similar to this with an
Exception object (or in fact anything that subclasses
java.lang.Throwable)? In this case, the stack trace is filled
with the trace from when the exception was created. Typically,
that isn't what you want because you probably want to see the
exact trace for each exception, that is, when each exception
happened. In order to share exception objects in this way, you
have to refill the stack trace for the new stack when the
exception happens. The method of Throwable to do this is
fillInStackTrace.
Here's what the getMyObject pattern looks like after adjusting it
to work with exception objects:
MyExceptionObject myExceptionObject = null;
private synchronized MyExceptionObject
getMyExceptionObject() {
if (myExceptionObject == null) {
myExceptionObject = new MyExceptionObject();
} else {
myExceptionObject.fillInStackTrace();
}
return myExceptionObject;
}
Notice that you don't have to fill in the stack manually the
first time. It's done for you. You only have to fill in the
stack for subsequent occurrences.
At this point, you might ask why you would want to reuse
exception objects. One reason to reuse (or even just pre-create)
exception objects is to minimize the number of objects created
when an exception actually happens. Of course, filling the stack
does take resources, so this isn't completely free of the need
for memory resources. And, if you truly don't need the stack
trace, this pattern allows you to not bother filling it.
To demonstrate this behavior, the following program shows two
ways of reusing exception objects. For each approach, the
exception is printed three times. In the first case, the same
stack is shown three times, even though three different methods
print the trace. The latter case demonstrates the difference in
each stack when you refill the stack trace with each call.
import java.io.*;
public class ReuseException {
IOException exception1 = null;
private synchronized IOException
getException1() {
if (exception1 == null) {
exception1 = new IOException();
}
return exception1;
}
IOException exception2 = null;
private synchronized IOException
getException2() {
if (exception2 == null) {
exception2 = new IOException();
} else {
exception2.fillInStackTrace();
}
return exception2;
}
void exception1Method1() {
getException1().printStackTrace();
}
void exception1Method2() {
getException1().printStackTrace();
}
void exception1Method3() {
getException1().printStackTrace();
}
void exception2Method1() {
getException2().printStackTrace();
}
void exception2Method2() {
getException2().printStackTrace();
}
void exception2Method3() {
getException2().printStackTrace();
}
public static void main(String[] args) {
ReuseException reuse =
new ReuseException();
reuse.exception1Method1();
reuse.exception1Method2();
reuse.exception1Method3();
System.out.println("---");
reuse.exception2Method1();
reuse.exception2Method2();
reuse.exception2Method3();
}
}
When you run the program, your output should look something like
this:
java.io.IOException
at ReuseException.getException1
(ReuseException.java:9)
at ReuseException.exception1Method1
(ReuseException.java:26)
at ReuseException.main
(ReuseException.java:51)
java.io.IOException
at ReuseException.getException1
(ReuseException.java:9)
at ReuseException.exception1Method1
(ReuseException.java:26)
at ReuseException.main
(ReuseException.java:51)
java.io.IOException
at ReuseException.getException1
(ReuseException.java:9)
at ReuseException.exception1Method1
(ReuseException.java:26)
at ReuseException.main
(ReuseException.java:51)
--java.io.IOException
at ReuseException.getException2
(ReuseException.java:18)
at ReuseException.exception2Method1
(ReuseException.java:38)
at ReuseException.main
(ReuseException.java:55)
java.io.IOException
at ReuseException.getException2
(ReuseException.java:20)
at ReuseException.exception2Method2
(ReuseException.java:42)
at ReuseException.main
(ReuseException.java:56)
java.io.IOException
at ReuseException.getException2
(ReuseException.java:20)
at ReuseException.exception2Method3
(ReuseException.java:46)
at ReuseException.main
(ReuseException.java:57)
For more information about working with exceptions, see the lesson
"Handling Errors with Exceptions" in the Java Tutorial
(http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html).
Also see the documentation for the Throwable class
(http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Throwable.html).
. . . . . . . . . . . . . . . . . . . . . . .
IMPORTANT: Please read our Terms of Use, Privacy, and Licensing
policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html
* FEEDBACK
Comments? Send your feedback on the Core Java Technologies
Tech Tips to:
jdc-webmaster@sun.com
* SUBSCRIBE/UNSUBSCRIBE
Subscribe to other Java developer Tech Tips:
- Enterprise Java Technologies Tech Tips. Get tips on using
enterprise Java technologies and APIs, such as those in the
Java 2 Platform, Enterprise Edition (J2EE).
- Wireless Developer Tech Tips. Get tips on using wireless
Java technologies and APIs, such as those in the Java 2
Platform, Micro Edition (J2ME).
To subscribe to these and other JDC publications:
- Go to the JDC Newsletters and Publications page,
(http://developer.java.sun.com/subscription/),