Java Reference
In-Depth Information
Java will then use a slightly different form of HTTP than the examples in this topic.
However, to the Java programmer, the difference is irrelevant. As long as you're using
the URLConnection class instead of raw sockets and as long as the server supports
chunked transfer encoding, it should all just work without any further changes to your
code. However, chunked transfer encoding does get in the way of authentication and
redirection. If you're trying to send chunked files to a redirected URL or one that requires
password authentication, an HttpRetryException will be thrown. You'll then need to
retry the request at the new URL or at the old URL with the appropriate credentials;
and this all needs to be done manually without the full support of the HTTP protocol
handler you normally have. Therefore, don't use chunked transfer encoding unless you
really need it. As with most performance advice, this means you shouldn't implement
this optimization until measurements prove the nonstreaming default is a bottleneck.
If you do happen to know the size of the request data in advance, you can optimize the
connection by providing this information to the HttpURLConnection object. If you do
this, Java can start streaming the data over the network immediately. Otherwise, it has
to cache everything you write in order to determine the content length, and only send
it over the network after you've closed the stream. If you know exactly how big your
data is, pass that number to the setFixedLengthStreamingMode() method:
public void setFixedLengthStreamingMode ( int contentLength )
public void setFixedLengthStreamingMode ( long contentLength ) // Java 7
Because this number can actually be larger than the maximum size of an int , in Java 7
and later you can use a long instead.
Java will use this number in the Content-length HTTP header field. However, if you
then try to write more or less than the number of bytes given here, Java will throw an
IOException . Of course, that happens later, when you're writing data, not when you
first call this method. The setFixedLengthStreamingMode() method itself will throw
an IllegalArgumentException if you pass in a negative number, or an IllegalSta
teException if the connection is connected or has already been set to chunked transfer
encoding. (You can't use both chunked transfer encoding and fixed-length streaming
mode on the same request.)”
Fixed-length streaming mode is transparent on the server side. Servers neither know
nor care how the Content-length was set, as long as it's correct. However, like chunked
transfer encoding, streaming mode does interfere with authentication and redirection.
If either of these is required for a given URL, an HttpRetryException will be thrown;
you have to manually retry. Therefore, don't use this mode unless you really need it.
Search WWH ::




Custom Search