本文介绍了下载二进制数据时,Apache HTTPClient 4.x CloseableHttpClient的大小错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache HttpClient 4.5.1下载".tgz"文件,并且正在Windows上运行客户端程序.

运行时,下载的文件大小为4,423,680(由于大小错误而无法打开).但是该文件的实际大小为4,414,136(使用"wget").

当我使用DefaultHttpClient(不建议使用)而不是CloseableHttpClient(所有其他代码都相同)时,问题消失了.

导致问题的代码:

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

When I run, I get the file downloaded with a size 4,423,680 (and it can't open because of the wrong size). But the actual size of the file is 4,414,136 (using "wget").

The problem goes away when I use DefaultHttpClient (deprecated) instead of CloseableHttpClient (all other code being the same).

Code that created 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 problem:

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

DefaultHttpClient已弃用,但似乎工作正常.
不了解CloseableHttpClient出了什么问题.

DefaultHttpClient is deprecated, but it seems to work fine.
Don't understand what is wrong with the CloseableHttpClient.

推荐答案

请尝试使用此代码段,看看是否仍然获得不同的文件大小.

Please try out this code snippet and see if you still get a different file size.

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);
        }
    }
}

这篇关于下载二进制数据时,Apache HTTPClient 4.x CloseableHttpClient的大小错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:06