Java Reference
In-Depth Information
else {
int chunkSize = 512;
int index = 0;
int readLength = 0;
data = new byte[chunkSize];
do {
if (data.length < index + chunkSize) {
byte[] newData = new byte[index + chunkSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
readLength = is.read(data, index, chunkSize);
index += readLength;
} while (readLength == chunkSize);
length = index;
}
…
} catch (Exception e) {…}
finally {
try {
if (is != null) is.close();
if (os != null) os.close();
if (hc != null) hc.close();
}
catch (Exception e) {…}
}
}
The setup using the GCF is exactly the same; the only difference is that this time the
code casts the result to an
HttpConnection
. The code then sets the request method to
POST
using
setRequestMethod
, and it adds an additional header to the request describing the
content type. On most implementations, the process of obtaining an output stream for the
request will cause the
HttpConnection
to move from the
setup
to the
connected
state; the
remote server is now waiting for the application to write the object body for the
POST
request. The code does this by first obtaining the output stream on the connection using
openOutputStream
, and then by writing a simple form-encoded name-value pair. Even if
the implementation buffers the headers and object body you've prepared using the
HttpConnection
instance and
OutputStream
, the
HttpConnection
must
open the connection,
send the request, and read the HTTP response headers when you invoke
getResponseCode
.
At this point, the connection is definitely in the
connected
state, and you can obtain infor-
mation about the result using connection methods such as
getLength
, as this code does to
determine the length of the resulting object body. The remainder of the code is the same as