java - Apache HttpUtils 下载文件
问题描述
我正在使用以下代码下载文件并计算长度,但返回值(长度)始终为 -1
private long getContentLength(String url) {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
System.out.println("Content length was: " + httpEntity.getContentLength() + " and code: " + httpResponse.getStatusLine().getStatusCode());
return httpEntity.getContentLength();
}
正在下载的文件:
boolean download100MBFile() {
getContentLength("http://cachefly.cachefly.net/100mb.test");
return true;
}
HTTP 响应代码为:200
该文件是从浏览器下载的,因此该文件没有问题。这里出了什么问题?
解决方案
Victor 的评论促使我使用流。这是有效的更新代码:
private long getContentLength(String url) {
outputStream.reset();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024 * 1024 * 1024);
try {
httpEntity.writeTo(outStream);
} catch (IOException ex) {
logException(ex);
return -1;
}
return outStream.size();
}
推荐阅读
- javascript - 使用 Javascript 调用函数背后的代码
- spring-boot - 具有 oauth 安全性的资源服务器控制器的 Spring Boot 集成测试
- ruby-on-rails - 在 rails_admin 中添加下拉菜单 未显示同一页面的其他表单字段
- ansible - 如何使用ansible对gce实例执行shell脚本
- asp.net-core - 如何更改网络核心路由器前缀
- python - 如何在列表中找到一对数字,其总和为给定数字
- mysql - 将 MariaDb 查询转换为 MySQL
- apache-kafka - 如何在 .yml 中为反序列化提供多个受信任的包?
- c# - 尝试安装应用程序 ApplicationInsights 包时,我遇到了一些错误
- javascript - 将从数组中随机选择的相同颜色分配给具有相同类的所有元素