Java Reference
In-Depth Information
•
Setup
: You can set request parameters, including the method.
•
Connected
: The request method and parameters have been sent, and the response is
requested.
•
Closed
: The HTTP connection has been terminated.
Unlike other types of connections, you need to know what state an
HttpConnection
is in, because certain methods will only work when the connection is in the proper
state. For example, you can't set the method type the connection should use once the
connection is in the
connected
state, because the connection has already sent the
request. The transition from
setup
to
connected
occurs when you invoke any method
that requires the connection to exchange data, such as opening a stream for reading or
writing to the connection.
While the connection is in the setup state, you can set the request method using
the connection's
setRequestMethod
method, passing one of
HttpConnection.GET
,
HttpConnection.POST
, or
HttpConnection.HEAD
. You can also specify an arbitrary request
header for the request, such as the MIME content type being provided. You do this
using the connection's
setRequestProperty
method, passing the name of the request
header and the value as strings, like this:
hc.setRequestProperty("Content-Type", "application/x-urlformencoded");
Many of the
HttpConnection
methods have direct correspondence with HTTP
response headers, including the following methods:
•
getDate
: Returns the value of the
Date
header as a time in seconds since the begin-
ning of the epoch
•
getExpiration
: Returns when the resource will expire, as indicated by the
Expires
header as a time in seconds since the beginning of the epoch
•
getLastModified
: Returns when the resource was last modified, as indicated by the
Last-Modified
header as a time in seconds since the beginning of the epoch
•
getResponseCode
: Returns the three-digit HTTP response code
•
getResponseMessage
: Returns the HTTP response message, if any
•
getHeaderField
: Returns the value of a specific HTTP header by name
You can also enumerate all of the response headers using the
getHeaderField
and
getHeaderFieldKey
methods by passing an integer; they return the value and name of the
n
th header, treating the block of response headers as a single array.