zoukankan      html  css  js  c++  java
  • 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;
            } 
        }
  • 相关阅读:
    11.10 安装GMONE3,卸载 UNITY和UNITY 2D
    Ubuntu 11.10 使用Gnome3 快捷键Alt+F2无效的解决办法
    Ioc容器应用浅析EasyJF学习
    JPA批注参考
    MVC(Model/View/Controller)EasyJF学习
    Subversion使用手記
    Eclipse 插件 esourceBundleEditor
    用 Subversion 构建版本控制环境
    TortoiseSVN使用
    自信的真正含义NLP
  • 原文地址:https://www.cnblogs.com/yejiurui/p/3200396.html
Copyright © 2011-2022 走看看