问题描述
我正在使用 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 下载二进制数据时大小错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!