Java Reference
In-Depth Information
whether to follow redirects, get the response code and message, and figure out whether
a proxy server is being used. It also includes several dozen mnemonic constants match‐
ing the various HTTP response codes. Finally, it overrides the
getPermission()
method
from the
URLConnection
superclass, although it doesn't change the semantics of this
method at all.
Because this class is abstract and its only constructor is protected, you can't directly
create instances of
HttpURLConnection
. However, if you construct a
URL
object using
an
http
URL and invoke its
openConnection()
method, the
URLConnection
object re‐
turned will be an instance of
HttpURLConnection
. Cast that
URLConnection
to
HttpURL
Connection
like this:
URL
u
=
new
URL
(
"http://lesswrong.com/"
);
URLConnection
uc
=
u
.
openConnection
();
HttpURLConnection
http
=
(
HttpURLConnection
)
uc
;
Or, skipping a step, like this:
URL
u
=
new
URL
(
"http://lesswrong.com/"
);
HttpURLConnection
http
=
(
HttpURLConnection
)
u
.
openConnection
();
The Request Method
When a web client contacts a web server, the first thing it sends is a request line. Typically,
this line begins with
GET
and is followed by the path of the resource that the client wants
to retrieve and the version of the HTTP protocol that the client understands. For ex‐
ample:
GET /catalog/jfcnut/index.html HTTP/1.0
However, web clients can do more than simply
GET
files from web servers. They can
POST
responses to forms. They can
PUT
a file on a web server or
DELETE
a file from a
server. And they can ask for just the HEAD of a document. They can ask the web server
for a list of the
OPTIONS
supported at a given URL. They can even
TRACE
the request
itself. All of these are accomplished by changing the request method from
GET
to a
different keyword. For example, here's how a browser asks for just the header of a docu‐
ment using
HEAD
:
HEAD /catalog/jfcnut/index.html HTTP/1.1
Host: www.oreilly.com
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: close
By default,
HttpURLConnection
uses the
GET
method. However, you can change this
with the
setRequestMethod()
method:
public void setRequestMethod(String method) throws ProtocolException
The method argument should be one of these seven case-sensitive strings: