getContentLength 总是=-1,都不知道怎么改了,求助,都烦了一天了

wuxia2001 2012-03-04 06:09:44
下面是代码:
/**
* 从服务器上取出更新里
* @param path
* @param pd
* @return
* @throws Exception
*/

public File getFileFromServer(String path,int i) throws Exception{
//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url = new URL(path);
//num++;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
int connl =conn.getContentLength();
System.out.println("++++"+conn.getResponseCode());
//获取到文件的大小
//pd.setMax(100);
InputStream is = conn.getInputStream();
String patha =Comments.BasePath+Comments.DownLoadPath+downloadInfos.get(i).fileName;
File file = new File(patha);
if(!file.exists()){
try {

new File(patha.substring(0, patha.lastIndexOf(File.separator))).mkdirs();
file.createNewFile();
Log.i("creatFileIfNotExits", "Path:"+patha+"creat success");
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建失败"+e.getMessage());
Log.i("creatFileIfNotExits","Path:"+patha+"&"+e.getMessage());
}
}
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);

byte[] buffer = new byte[1024];
int len ;
int total=0;
while((len =bis.read(buffer))!=-1){
fos.write(buffer, 0, len);
System.out.println("len is "+len);
total+= len;
//获取当前下载量
System.out.println("total is "+total);
System.out.println("max is "+connl);
prog[i] = (total*100/connl);
System.out.println("this is progress :"+prog[i]);
//pd.setProgress(progress);

}
//pd.setProgress(295);

fos.close();
bis.close();
//conn.disconnect();
is.close();

return file;
} else{
return null;
}
}

在conn.getContentLength()这里的输出值永远是-1,但conn.getResponseCode()是200,文件也下载成功了,就是长度获取不到,长度一直是-1,释放资源吧,我应该也是释放了的吧。求人帮助。。。。。。。。
...全文
1390 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenghu1982 2012-08-07
  • 打赏
  • 举报
回复
返回流必须包含contentLength信息
参考 struts2
@Action( value = "downApp", results={@Result(type="stream",
params={"contentType","application/octet-stream",
"contentLength","${contentLength}",
"inputName","imageStream",
"contentDisposition","attachment;filename=${fileName}",
"bufferSize","4096" })})
danielinbiti 2012-03-04
  • 打赏
  • 举报
回复
下载成功和返回-1不冲突,getContentLength获取文件大小的原理就是头中的content length属性,如果服务器没有或者流不支持,就返回-1了,下载文件不影响。
可以文件下完后本地根据下载的字节计算文件大小。
tony-杨 2012-03-04
  • 打赏
  • 举报
回复
会不会服务器给你返回的头信息中ContentLength本身就是错误的。。。。。
你直接打印头信息看看:可以用getHeaderFieldKey跟getHeaderField

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧