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;
            } 
        }
  • 相关阅读:
    mysql最后一个内容orm
    mysql第五天:
    mysql第二天 数据的增删改查补充及外键
    MYsql 初识
    第二天openc的内容:图片的缩放、旋转、格式转换
    第二个内容第一天 opencv的基本内容:
    第五十七天 bom 的新知识
    第五十六天jQurey的内容新增:
    第五十五天jQery内容的进阶
    windows11 upgrade
  • 原文地址:https://www.cnblogs.com/yejiurui/p/3200396.html
Copyright © 2011-2022 走看看