下面是代码:
/**
 * 从服务器上取出更新里
 * @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,释放资源吧,我应该也是释放了的吧。求人帮助。。

解决方案 »

  1.   

    会不会服务器给你返回的头信息中ContentLength本身就是错误的。。
    你直接打印头信息看看:可以用getHeaderFieldKey跟getHeaderField
      

  2.   

    下载成功和返回-1不冲突,getContentLength获取文件大小的原理就是头中的content length属性,如果服务器没有或者流不支持,就返回-1了,下载文件不影响。
    可以文件下完后本地根据下载的字节计算文件大小。
      

  3.   

    返回流必须包含contentLength信息
    参考 struts2
    @Action( value = "downApp", results={@Result(type="stream",   
                        params={"contentType","application/octet-stream",   
    "contentLength","${contentLength}",   
                                "inputName","imageStream",   
                                "contentDisposition","attachment;filename=${fileName}",   
                                "bufferSize","4096"  })})