Search code examples
javaapachehttpresponsecontent-length

How to Ignore the content-length exception while writing (downloading) a file from server response?


I am making a request to a server, which I have no control over. It returns a downloadable response. I am downloading the file in client as follows

File backupFile = new File("Download.zip");

CloseableHttpResponse response = ...;

try(InputStream inputStream = response.getEntity().getContent()) {
    try(FileOutputStream fos = new FileOutputStream(backupFile)) {
        int inByte;
        while((inByte = inputStream.read()) != -1) {
            fos.write(inByte);
        }
    }
}

I am getting the following exception:

Premature end of Content-Length delimited message body (expected: 548846; received: 536338
    at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:142)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:120)

Premature end of Content-Length delimited message body (expected:

I went through the above SO question, but that question and its answers address a serious bug, where the server doesn't deliver what it promised. Also I am not closing the client before downloading the file is complete.

In my case, the file (zip file) is perfect, just that the estimate of size is off by a minute fraction.

Reported this to the server maintainer, but I was wondering if there was a way to ignore this exception. Assuming the checks on the downloaded file is done by self.


Solution

  • Assuming the file is complete as is, you can simply catch the exception, flush the rest of the stream, close it, and the file should be written in its entirety as given by the server. Of course if the file is only partially complete, then you won't be able to open the file as a zip file in any context, so do be sure that the file is correct as it is being sent and that it is only a problem of content length.