public boolean downLoadFile2(String fileurl, String savepath)
{//Things need to do:
//Set connection timeout
//Try more times to download
//Catch a general Exception is not so good
//...
try
{
int httpStatusCode;
URL url =new URL(fileurl);
URLConnection conn = url.openConnection();
conn.connect();
HttpURLConnection httpconn =(HttpURLConnection)conn;
httpStatusCode =httpconn.getResponseCode();
if(httpStatusCode!=HttpURLConnection.HTTP_OK)
{//HttpURLConnection return an error code
System.out.println("Connect to "+fileurl+" failed,return code:"+httpStatusCode);
return false;
}
int filelen = conn.getContentLength();
InputStream is = conn.getInputStream();
byte[] tmpbuf=new byte[1024];
File savefile =new File(savepath);
if(!savefile.exists())
savefile.createNewFile();
FileOutputStream fos = new FileOutputStream(savefile);
int readnum = 0;
if(filelen<0)//for http://www.csdn.net/expert/topic/204/204361.shtm, conn.getContentLength() return -1.
{
while(readnum>-1)
{
readnum = is.read(tmpbuf);
if(readnum>0)
fos.write(tmpbuf,0,readnum);
}
}
else
{
int readcount =0;
while(readcount<filelen&&readnum!=-1)
{
readnum=is.read(tmpbuf);
if(readnum>0)
{
fos.write(tmpbuf,0,readnum);
readcount =readcount +readnum;
}
}
if(readcount<filelen)
{
System.out.println("download error");
is.close();
fos.close();
savefile.delete();
return false;
}
}
fos.flush();
fos.close();
is.close();
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
return true;
}