首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

getContentLength 总是=-1,都不知道如何改了,都烦了一天了

2012-09-11 
getContentLength 总是=-1,都不知道怎么改了,求助,都烦了一天了下面是代码:/** * 从服务器上取出更新里 *

getContentLength 总是=-1,都不知道怎么改了,求助,都烦了一天了
下面是代码:
/**
* 从服务器上取出更新里
* @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,释放资源吧,我应该也是释放了的吧。求人帮助。。。。。。。。


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

热点排行