Note: this question is closely related to Is it acceptable for a server to send a HTTP response before the entire request has been received? with the difference that (1) I'm not sending an error, I'm sending a 200 OK, and (2) I control both the client and server, so don't really care about browser support.
Context: I am implementing a Java HTTP client and server for managing files. In particular an "upload" query contains a file path and the file body, and the server responds with a numerical identifier for the file. However if a file with the same path has already been uploaded, the server will simply respond with the previously generated identifier.
Concretely: if I write the server as follows (sparkjava)
put(url, (req, res) -> {
Item existing = lookForExistingItem(req);
if (existing != null) {
return existing.getId();
}
/* Otherwise, consume input, save, generate id and return that */
});
... then the server will respond with the id and close the connection before the client finished sending data. If I write the client as follows:
final HttpURLConnection connection = (HttpURLConnection) new URL(...).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
ByteStreams.copy(fileInput, connection.getOutputStream());
final String response = CharStreams.toString(new InputStreamReader(connection.getInputStream()));
then an IOException
is thrown during the copy
operation due to the closed connection. After that point I am not able to access the connection's InputStream
anymore.
My Question: how can I make this work? If I change the server to consume the whole input and throw it away, it works, but it feels like wasting resources (some of the files being uploaded may be videos weighing hundreds of megabytes). Is there any way to change the client code to deal with that scenario?