HttpURLConnection 下载代码

private int downloadFile(final String apkurl, final String apkname) {        
        Log.e(LOGTAG, "downloadApkBackground..apkurl="+apkurl+"; filePath="+apkname);
        File file = new File(apkname);  
        FileOutputStream out = null;
        InputStream is = null;
        int fileLength = 0;
        long count = 0;
        try{
            URL url = new URL(apkurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(6*1000);  
            conn.setRequestMethod("GET"); 
            conn.setDoOutput(true); 
            if(file.exists()){
                count = file.length();
            }
            
            conn.setRequestProperty("User-Agent", "NetFox");
            conn.setRequestProperty("RANGE", "bytes=" + count + "-");
            conn .setRequestProperty("Accept-Encoding", "identity"); 
            out = new FileOutputStream(file, true); 
            is = conn.getInputStream();
            fileLength = conn.getContentLength();  
            Log.e(LOGTAG, "downloadApkBackground...count="+count+"; fileLength="+fileLength);
            
            byte buf[] = new byte[4 * 1024];
            int size = 0;
            
            while ((size = is.read(buf)) != -1) {  //down and cached
                try {
                    out.write(buf, 0, size);
                    count += size;
                    if(count >= fileLength){
                        return UPDATE_FAIL_WITH_SUCCESS;
                    }
                    
                    //Log.e(LOGTAG, "downloadApkBackground..count="+count);
                    //publishProgress(count, fileLength);   
                    out.flush();
                } catch (Exception e) {        
                    e.printStackTrace();
                    mDownloadIsError = true;
                    return UPDATE_FAIL_WITH_FAIL_UNKONWN;
                }
            }
            return UPDATE_FAIL_WITH_SUCCESS;
        }catch (MalformedURLException e) {
            mDownloadIsError = true;
            e.printStackTrace();
        }catch (IOException e) {
            mDownloadIsError = true;
            e.printStackTrace();
        }finally{  
            try{  
                out.close();  
                is.close();  
            }  
            catch(Exception e){  
                mDownloadIsError = true;
                e.printStackTrace();  
            }  
        }
        
        return UPDATE_FAIL_WITH_FAIL_UNKONWN;
    }

 

posted @ 2016-08-28 16:10  舞阳  阅读(246)  评论(0编辑  收藏  举报