Apache HTTPClient 4.x CloseableHttpClient gets the wrong size when loading binary data

I am using Apache HttpClient 4.5.1 to download the ".tgz" file and I am running my client program on Windows.

When I run, I get a file loaded with size 4 423 680 (and it cannot open due to the wrong size). But the actual file size is 4,414,136 (using "wget").

The problem disappears when I use DefaultHttpClient (deprecated) instead of CloseableHttpClient (all other codes are the same).

The code that generated the problem:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
CloseableHttpClient httpClient = HttpClients.createDefault();
(or)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// the following code is the same in both cases 
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
try {
   BufferedInputStream bis = new BufferedInputStream(entity.getContent());
   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
   int inByte;
   while ((inByte = bis.read()) != -1 ) {
                bos.write(inByte);
   }
}
....

Code that resolved the issue:

 import org.apache.http.impl.client.DefaultHttpClient;
 ...
 HttpClient httpClient = new DefaultHttpClient();
 ... <same code>....

DefaultHttpClient is deprecated, but it works fine.
I don't understand what is wrong with CloseableHttpClient.

0
2

.

, , , try-with-resources finally try-catch

try(HttpResponse response = httpClient.execute(httpGet)) {
....

finally
{
  response.close();
}

, , . , , .

-. , , , . , bos .

. . , . , , Http Client .

+1

, .

CloseableHttpClient httpClient = HttpClientBuilder.create()
        .disableContentCompression()
        .build();
HttpGet get = new HttpGet(url);
try (CloseableHttpResponse response = httpClient.execute(get)) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            entity.writeTo(outputStream);
        }
    }
}
0

Source: https://habr.com/ru/post/1660506/


All Articles