Utils--封装好的下载图片的方法

/**
     * 封装下载图片方法
     * @param url 下载地址
     * @param filename 
     * @return 下载成功为true
     */
    
    public boolean downfile(String url,String filename,String filePath){        
        InputStream is=null;
        FileOutputStream out=null;
        HttpGet httpGet = new HttpGet(url); 
        try {
        HttpParams httpParameters = new BasicHttpParams();  
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); 
        
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 
        HttpResponse response;
            response = httpClient.execute(httpGet);
        
        
        if (response.getStatusLine().getStatusCode() ==  HttpStatus.SC_OK){
            HttpEntity entity = response.getEntity();          
            is = entity.getContent(); 
            long fileSize = entity.getContentLength();//根据响应获取文件大小
            if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
            if (is == null) throw new RuntimeException("stream is null");
            File file = new File(Constants.filePath);        
            if(!file.exists()){
                file.mkdir();
            }
            file = new File(filePath);    
            if(!file.exists()){
                file.mkdir();
            }
            File fileOut = new File(filename);
            if(!fileOut.exists()){
//                new File(filePath).mkdir();
                fileOut.createNewFile(); 
            }
            out = new FileOutputStream(fileOut);   
            byte[] buf = new byte[1024];                 
            do{
                int numread = is.read(buf);
                if (numread == -1)
                {
                    break;
                }
                out.write(buf, 0, numread);
                
            
            } while (true);
         }else{
             return false;
         }                   
        is.close();   
        out.close();
        return true;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } 
    }
posted @ 2013-07-19 13:39  Andye  阅读(544)  评论(0编辑  收藏  举报