Java Reference
In-Depth Information
<body bgcolor="#FFFFFF">
<h1>404 FILE NOT FOUND</h1>
Rest of error message follows...
There are many other, less common responses. For instance, code 301 indicates that the
resource has permanently moved to a new location and the browser should redirect
itself to the new location and update any bookmarks that point to the old location. For
example:
HTTP/1.1 301 Moved Permanently
Connection: Keep-Alive
Content-Length: 299
Content-Type: text/html; charset=iso-8859-1
Date: Sat, 04 May 2013 14:20:58 GMT
Keep-Alive: timeout=5, max=200
Location: http://www.cafeaulait.org/
Server: Apache
Often all you need from the response message is the numeric response code.
HttpURL
Connection
also has a
getResponseCode()
method to return this as an
int
:
public
int
getResponseCode
()
throws
IOException
The text string that follows the response code is called the
response message
and is
returned by the aptly named
getResponseMessage()
method:
public
String
getResponseMessage
()
throws
IOException
HTTP 1.0 defined 16 response codes. HTTP 1.1 expanded this to 40 different codes.
Although some numbers, notably 404, have become slang almost synonymous with
their semantic meaning, most of them are less familiar. The
HttpURLConnection
class
includes 36 named constants such as
HttpURLConnection.OK
and
HttpURLConnec
tion.NOT_FOUND
representing the most common response codes. These are summar‐
ized in
Table 6-1
.
Example 7-16
is a revised source viewer program that now includes
the response message.
Example 7-16. A SourceViewer that includes the response code and message
import
java.io.*
;
import
java.net.*
;
public
class
SourceViewer3
{
public
static
void
main
(
String
[]
args
)
{
for
(
int
i
=
0
;
i
<
args
.
length
;
i
++)
{
try
{
// Open the URLConnection for reading
URL
u
=
new
URL
(
args
[
i
]);
HttpURLConnection
uc
=
(
HttpURLConnection
)
u
.
openConnection
();
int
code
=
uc
.
getResponseCode
();
String
response
=
uc
.
getResponseMessage
();
System
.
out
.
println
(
"HTTP/1.x "
+
code
+
" "
+
response
);