为了账号安全,请及时绑定邮箱和手机立即绑定

初始化线程里 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();

}

}

}

}


正在回答

3 回答

如果网络连接失败会导致这个问题,你先试试在浏览器里能不能打开文件的URL,如果打不开就是网络地址的问题,换个文件下载地址试下

0 回复 有任何疑惑可以回复我~

HTML?PHP编码规范使用UTF-8

orbha

0 回复 有任何疑惑可以回复我~

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

conn.setRequestMethod("POST");
//把提交从GET改为POST


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Android-Service系列之断点续传下载
  • 参与学习       20444    人
  • 解答问题       87    个

想升职加薪么?本章课程你值得拥有,满满的干货,学起来吧

进入课程

初始化线程里 length=conn.getContentLength();返回值一直是-1

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信