Java apachehttputils下载一个文件
我使用以下代码下载文件并计算长度,但返回值(length)始终为-1Java apachehttputils下载一个文件,java,apache-httpclient-4.x,Java,Apache Httpclient 4.x,我使用以下代码下载文件并计算长度,但返回值(length)始终为-1 private long getContentLength(String url) { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet); } catch (Excep
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
该文件是从浏览器下载的,因此该文件没有问题。这里出了什么问题?维克托的评论激发我使用流。 以下是最新的代码,它可以工作:
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();
}
有例外吗?也可能是拒绝该文件的服务器端。是否设置用户代理或其他标题?编辑:wget与此URL一起开箱即用,因此它可能不是标题…您是否尝试打印HTTP响应代码?如果内容大小未知,请检查(流)。所以,您可以将您的内容加载到临时文件中,并获取该文件的大小。