Java Reference
In-Depth Information
The
HttpConnection
class also contains some of the utility functions for examining
URLs. These utility functions let you determine the scheme, host name, port, and file a
URL contained when the GCF created the
HttpConnection
instance. These
HttpConnection
methods include
getProtocol
,
getHost
,
getPort
, and
getFile
. You can also determine the
URL to which a specific
HttpConnection
refers by invoking its
getURL
method.
Probably the most common reason for needing to use an
HttpConnection
instead of a
ContentConnection
is when you need to submit data for processing, like user input to a
web service. This may involve using the HTTP
POST
method instead of
GET
. You use an
HttpConnection
and get its
OutputStream
in order to write the data to the server, as shown
in Listing 12-9.
Listing 12-9.
Sending Data to the Server
void run() throws IOException {
String url = "http://www.noplace.com/do";
HttpConnection hc = null;
DataInputStream is = null;
OutputStream os = null;
int rc;
try {
hc = (HttpConnection)Connector.open(url);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-Type",
"application/x-urlformencoded");
os = hc.openOutputStream();
os.write("name=value\n".getBytes());
rc = hc.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = hc.openInputStream();
int length = (int)hc.getLength();
byte[] data = null;
if (length != -1) {
data = new byte[length];
is.readFully(data);
}