HTTP POST Basics
|By Eric Giguere, June 8, 2004|
The Hypertext Transfer Protocol (HTTP) is the most ubiquitous of the Internet protocols. Although seen primarily as a means to fetch pages of Hypertext Markup Language (HTML) content for display in a web browser, HTTP is really a general-purpose transport for any type of data. That versatility is why HTTP support is a fundamental feature of the Mobile Information Device Profile (MIDP). In fact, on many devices HTTP is the only network protocol available.
HTTP is a request-response protocol. Various types of requests are possible, each identified by a different HTTP method. MIDP supports two of those methods, GET and POST.
A GET request fetches data from a web server based solely on a URL value and a set of HTTP headers. Here's an example of what a web server receives when a client makes a GET request:
GET /index.html?userid=joe&password=guessme HTTP/1.1
In contrast, a POST request sends additional data to the web server, specified after the URL, the headers, and a blank line to indicate the end of the headers. An example:
POST /login.jsp HTTP/1.1
You can generate this second request with the following code:
The code is similar to the GET case, but now a call to
setRequestMethod() changes the request type to POST, and three calls to
setRequestProperty() set the headers. The
Content-Type headers are critical because they tell the web server how many bytes of data to expect, and what kind, identified by a MIME type.
When posting data, setting the
Content-Length header isn't obligatory; the HTTP client implementation should use "chunked encoding" - part of the HTTP 1.1 specification - to transfer the data to the web server. Set the length if you can, though; implementations of chunked encoding vary from one web server to the next.
After setting the headers the code sends the data itself, using the connection's output stream. You can send any kind of data as long as you identify it properly. In MIDP clients the two most popular MIME types are
application/octet-stream, to send raw binary data, and
application/x-www-form-urlencoded, to send name-value pairs.
The latter type mimics what a web browser sends when the user submits a form. You send the data for a "form post" in the same format you use for URL query parameters, except that you drop the leading ? character. Just as when sending a query, you must URL-encode form-post data. Unfortunately, MIDP doesn't supply an encoder. You must write your own, or use one of several freely available implementations.
In general, you'll use POST requests to transfer data from a MIDP client to a web server, because the web server doesn't log the data you send, and you can send binary data - handy for transferring byte arrays or serialized Java objects. You also avoid the limits on URL length that GET requests face if they include too many query parameters.