Webページの画像のキャプチャ

2944 ワード

簡単なWebサイトの画像キャプチャ機能
すべてjdkの基本的な机能を使って、いかなるかばんでどんな効率を话さないでください、どんな规范、要したのはすぐに理解して、持っていて耻ずかしくて、正则さえ使いたくなくてオープンソースの爬虫类のソフトウェアを使いません...
主に二つの部分に分かれている
1.接続を特定
public class GetWebContent {
    /**
     *   html  
     * @param domain
     * @return
     */
    public static String getWebCon(String path) {
        // System.out.println("      ...("+domain+")");
        StringBuffer sb = new StringBuffer();
        try {
            java.net.URL url = new java.net.URL(path);
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
        } catch (Exception e) { // Report any errors that arise
            sb.append(e.toString());
            System.err.println(e);
            System.err
                    .println("Usage:   java   HttpClient      []");
        }
        return sb.toString();
    }
     
    /**
     *         
     * @param path       
     * @param begin       
     * @param end       
     */
    public static void uploadImage(String path,String begin,String end){
        Map map=new HashMap<>();
        String a=getWebCon(path);
        String[] as=a.split(begin);
        for (int j = 1; j < as.length-1; j++) {
            String xxx = as[j].split(end)[0];
            String url=begin+xxx+end;
            if (map.containsKey(url))  continue;
            try {
                DownloadImage.download(url);
                map.put(url, "111");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }
        
    }
}

2.画像のダウンロード
public class DownloadImage {
    
    private  static final String FILE_PATH="D:\\image\\";
 
    public static void download(String urlString) throws Exception {
        //   URL
        String filename=System.currentTimeMillis()+"-"+(int)(Math.random()*10000)+".jpg";
        String savePath=FILE_PATH;
        URL url = new URL(urlString);
        //     
        URLConnection con = url.openConnection();
        //       5s
        con.setConnectTimeout(5*1000);
        //    
        InputStream is = con.getInputStream();
    
        // 1K     
        byte[] bs = new byte[1024];
        //         
        int len;
        //       
       File sf=new File(savePath);
       if(!sf.exists()){
           sf.mkdirs();
       }
       OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
        //     
        while ((len = is.read(bs)) != -1) {
          os.write(bs, 0, len);
        }
        //   ,      
        os.close();
        is.close();
    } 

}