初始化線程里 length=conn.getContentLength();返回值一直是-1
?class InitThread extends Thread {
private FileInfo mFileInfo = null;
public InitThread(FileInfo mFileInfo) {
this.mFileInfo = mFileInfo;
}
public void run() {
HttpURLConnection conn = null;
RandomAccessFile raf = null;
try {
URL url = new URL(mFileInfo.getUrl());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int length = -1;
if(conn.getResponseCode() == HttpStatus.SC_OK)
{
length = conn.getContentLength(); ? ? ? ? ? ? ? ? //獲得的值一直是-1,無法下載
}
if(length <=0)
{
return;
}
File dir = new File(DOWNLOAD_PATH);
if(!dir.exists())
{
dir.mkdir();
}
File file = new File(dir,mFileInfo.getFileName());
raf = new RandomAccessFile(file, "rwd");
raf.setLength(length);
mFileInfo.setLength(length);
mHandler.obtainMessage(MSG_INIT,mFileInfo).sendToTarget();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try {
raf.close();
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
2015-04-20
如果網絡連接失敗會導致這個問題,你先試試在瀏覽器里能不能打開文件的URL,如果打不開就是網絡地址的問題,換個文件下載地址試下
2015-10-12
getContentLength()方法是是從請求體中獲取數據,而GET是URL明文,API是這樣說的:Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.所有會一直放回-1