Java Reference
In-Depth Information
Java has two methods to configure redirection on an instance-by-instance basis. These
are:
public
boolean
getInstanceFollowRedirects
()
public
void
setInstanceFollowRedirects
(
boolean
followRedirects
)
If
setInstanceFollowRedirects()
is not invoked on a given
HttpURLConnection
, that
HttpURLConnection
simply follows the default behavior as set by the class method
HttpURLConnection.setFollowRedirects()
.
Proxies
Many users behind firewalls or using AOL or other high-volume ISPs access the Web
through proxy servers. The
usingProxy()
method tells you whether the particular
HttpURLConnection
is going through a proxy server:
public
abstract
boolean
usingProxy
()
It returns
true
if a proxy is being used,
false
if not. In some contexts, the use of a proxy
server may have security implications.
Streaming Mode
Every request sent to an HTTP server has an HTTP header. One field in this header is
the Content-length (i.e., the number of bytes in the body of the request). The header
comes before the body. However, to write the header you need to know the length of
the body, which you may not have yet. Normally, the way Java solves this catch-22 is by
caching everything you write onto the
OutputStream
retrieved from the
HttpURLCon
nection
until the stream is closed. At that point, it knows how many bytes are in the
body so it has enough information to write the Content-length header.
This scheme is fine for small requests sent in response to typical web forms. However,
it's burdensome for responses to very long forms or some SOAP messages. It's very
wasteful and slow for medium or large documents sent with HTTP
PUT
. It's much more
efficient if Java doesn't have to wait for the last byte of data to be written before sending
the first byte of data over the network. Java offers two solutions to this problem. If you
know the size of your data—for instance, you're uploading a file of known size using
HTTP
PUT
—you can tell the
HttpURLConnection
object the size of that data. If you don't
know the size of the data in advance, you can use chunked transfer encoding instead.
In chunked transfer encoding, the body of the request is sent in multiple pieces, each
with its own separate content length. To turn on chunked transfer encoding, just pass
the size of the chunks you want to the
setChunkedStreamingMode()
method before you
connect the URL:
public
void
setChunkedStreamingMode
(
int
chunkLength
)