Java Reference
In-Depth Information
getLength() — Returns a long value returning the actual length of the content in bytes. If
this information is not available, the method returns -1 .
The HTTPConnection specializes the ContentConnection interface further, adding support for
HTTP methods and header fields. Before we look into the additional methods in more detail, we need
to describe the three possible states of this type of connection:
• Setup—The connection to the server has not yet been established.
• Connected—All request parameters have been set and sent to the server, and the client expects
a response from the server.
• Closed—The connection is closed, and all methods invoked on the HTTPConnection will
throw an IOException . Note that the connection and all streams obtained should be closed.
Depending on the state, only a subset of the methods provided by HTTPConnection may be called
without causing a state transition or even an exception.
Note
A special feature of HTTP 1.1 that most HTTP 1.0 servers do not understand is chunked encoding.
Basically, chunked encoding means that parts of a request are sent separately with additional length
information. The additional length information is interpreted by HTTP 1.0 servers as content, letting
the server fail in interpreting the content. Some MIDP implementations such as the SUN wireless
toolkit switch to chunked encoding when the amount of data sent exceeds a fixed limit, or when the
flush() method is called on the output stream. In many cases, the problems with HTTP 1.0 servers
can be avoided by not calling flush() .
Request Properties
The setRequestMethod() can be used to set the connection to GET , POST , or HEAD only in the
Setup state. The same holds for setRequestProperty() , which sets the request headers that need
to be initialized before a connection is established. The following line contains an example for setting
the User-Agent header:
setRequestProperty ("User-Agent", "Profile/MIDP-1.0
Configuration/CLDC-1.0");
This call causes the following header line to be sent with the request when the connection is established:
User-Agent: Profile/MIDP-1.0 Configuration/CLDC-1.0
The HTTPConnection will change to the Connected state when one of the methods for sending and
receiving data, like openInputStream() or openOutputStream() , is called. The transition to
the Connected state is also performed when the header fields of the server response are accessed. For
that purpose, the getHeaderField() method can be used. T he following line of code would return
the String "Apache/1.3.14 (Unix)" for our example request:
String serverType = getHeaderField("Server");
The complete source code for creating the example request is as follows:
try {
HttpConnection httpConnection =
(HttpConnection) Connector.open ("http://www.leo.org/");
httpConnection.setRequestProperty
Search WWH ::




Custom Search