java 下载图片

@Test
	public void test() throws Exception {
		try{
			String cssPath = "E:/navStyle0.min.css";
			String css = FileUtils.readFileToString(new File(cssPath));
			String[] arr = StringUtils.substringsBetween(css,"background:url(", ")");
			String rootDir = "D:\\image";
			for (int i = 0; i < arr.length; i++) {
				String urlStr = arr[i];
				
				String httpUrl = "http://0.ss.faidns.com"+urlStr;
				String localFile = "E:" + arr[i];
				if(urlStr.indexOf("?")>0){
					localFile = localFile.split("v=")[0].replace("?","");
				}
				new File(localFile).getParentFile().mkdirs();
				FileOutputStream os  = new FileOutputStream(localFile);
				
				try{
					URL url = new URL(httpUrl);
					URLConnection connection = url.openConnection(); 
		            connection.setDoInput(true);  
		            connection.setDoOutput(true);  
		            connection.setUseCaches(false);  
		            connection.addRequestProperty("Accept", "image/gif, image/png, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");  
		            connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");  
		            connection.addRequestProperty("Accept-Encoding", "gzip, deflate");  
		            connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 2.0.50727; MS-RTC LM 8)");  
		            connection.connect();  					
					InputStream is = connection.getInputStream();
					Map map = connection.getHeaderFields();  
		            Iterator it = map.keySet().iterator();   
		              
		            boolean gzip = false;  
		            while(it.hasNext()) {  
		               Object type =  map.get(it.next());  
		               if(type.toString().indexOf("gzip") != -1){  
		                   gzip = true;  
		                   break;  
		               }  
		            }  
					byte [] buffer = new byte[1024];
					
					if(!gzip){  
		                int byteReaded = is.read(buffer);  
		                while (byteReaded != -1) {  
		                    os.write(buffer, 0, byteReaded);  
		                    byteReaded = is.read(buffer);  
		                }  
		            }else{  
		                GZIPInputStream gis = new GZIPInputStream(is);  
		                int byteReaded = 0;            
		                while ((byteReaded = gis.read(buffer)) != -1) {  
		                   os.write(buffer, 0, byteReaded);                    
		               }  
		            }    					
					int count = 0;
					while((count=is.read(buffer))>=0){
						os.write(buffer,0,count);
					}

					os.flush();
					os.close();
					is.close();
					
					
				}catch(Exception me){
					me.printStackTrace();
				}
				System.out.println(urlStr);
			}
		}catch(Exception me){
			me.printStackTrace();
		}			
	}


你可能感兴趣的:(java,下载图片)