Java Reference
In-Depth Information
Expiration date: Fri May 31 22:08:09 EDT 2013
Content-length: 83273
The content type of the file at
http://www.oreilly.com
is
text/html
. No content encoding
was used. The file was sent on Friday, May 31, 2013 at 6:08 P.M., Eastern Daylight Time.
It was last modified on the same day at 5:04 P.M. and it expires four hours in the future.
There was no Content-length header. Many servers don't bother to provide a Content-
length header for text files. However, a Content-length header should always be sent for
a binary file. Here's the HTTP header you get when you request the GIF image
http://
oreilly.com/favicon.ico
. Now the server sends a Content-length header with a value of
2294:
%
java HeaderViewer http://oreilly.com/favicon.ico
Content-type: image/x-icon
Date: Fri May 31 18:16:01 EDT 2013
Last modified: Wed Mar 26 19:14:36 EST 2003
Expiration date: Fri Jun 07 18:16:01 EDT 2013
Content-length: 2294
Retrieving Arbitrary Header Fields
The last six methods requested specific fields from the header, but there's no theoretical
limit to the number of header fields a message can contain. The next five methods inspect
arbitrary fields in a header. Indeed, the methods of the preceding section are just thin
wrappers over the methods discussed here; you can use these methods to get header
fields that Java's designers did not plan for. If the requested header is found, it is returned.
Otherwise, the method returns
null
.
public String getHeaderField(String name)
The
getHeaderField()
method returns the value of a named header field. The name
of the header is not case sensitive and does not include a closing colon. For example, to
get the value of the Content-type and Content-encoding header fields of a
URLConnec
tion
object
uc
, you could write:
String
contentType
=
uc
.
getHeaderField
(
"content-type"
);
String
contentEncoding
=
uc
.
getHeaderField
(
"content-encoding"
));
To get the Date, Content-length, or Expires headers, you'd do the same:
String
data
=
uc
.
getHeaderField
(
"date"
);
String
expires
=
uc
.
getHeaderField
(
"expires"
);
String
contentLength
=
uc
.
getHeaderField
(
"Content-length"
);
These methods all return
String
, not
int
or
long
as the
getContentLength()
,
getEx
pirationDate()
,
getLastModified()
, and
getDate()
methods that the preceding sec‐
tion did. If you're interested in a numeric value, convert the
String
to a
long
or an
int
.