I don't get a good understanding about HttpUrlConnection.setChunkedStreamingMode
, what is the effect of this mode?
I have following sample code:
HttpURLConnection conn = getHttpURLConnection(_url);
conn.setChunkedStreamingMode(4096); //4k
conn.setConnectTimeout(3000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = conn.getOutputStream();
byte[] buffer = new byte[1024 * 10];//10k
FileInputStream in= new FileInputStream(file); //Write the content of the file to the server
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
in.close();
Say, The file size is 101k, and I set the chunk size to be 4096.
The HttpUrlConnection will send 4096 bytes to the server every write? and 1k for the last time?
Note that I have used a 10k buffer to write to the outputstream, Does it matter that the chunk size and buffer size are not the same?
If I disable the ChunkedStreamMode in my code, what's the effect compared to the code that I have set 4096?
Yes you need to close the inputstream first and close httpconnection next. As per javadoc.
URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.
HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.
The getResponseMessage is a method of Java HttpURLConnection class. This method is used to get response code from HTTP response message. For example, if the response code from a server is HTTP/1.0 200 OK or HTTP/1.0 404 Not Found, it extracts the string OK and Not Found else returns null if HTTP is not valid.
- The HttpUrlConnection will send 4096 bytes to the server every write? and 1k for the last time?
Yes.
- Note that I have used a 10k buffer to write to the outputstream, Does it matter that the chunk size and buffer size are not the same?
No.
- If I disable the ChunkedStreamMode in my code, what's the effect compared to the code that I have set 4096?
The effect is that the entire output is buffered until you close, so that the Content-length header can be set and sent first, which adds a lot of latency and memory. Not recommended in the case of large files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With