Code for download video from Youtube on Java, Android

3 steps:

  1. Check the source code (HTML) of YouTube, you’ll get the link like this http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...

  2. Decode the url (remove the codes %2B, %25, etc), create a decoder with the codes and use the function Uri.decode(url) to replace invalid escaped octets

  3. Use the code to download stream:

        URL u = null;
        InputStream is = null;  
        
        try {
            u = new URL(url);
            is = u.openStream(); 
            HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
            int size = huc.getContentLength();                 
 
            if(huc != null) {
                String fileName = "FILE.mp4";
                String storagePath = Environment.getExternalStorageDirectory().toString();
                File f = new File(storagePath,fileName);
               
                FileOutputStream fos = new FileOutputStream(f);
                byte[] buffer = new byte[1024];
                int len1 = 0;
                if(is != null) {
                    while ((len1 = is.read(buffer)) > 0) {
                        fos.write(buffer,0, len1);  
                    }
                }
                if(fos != null) {
                    fos.close();
                }
            }                       
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {               
                if(is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                // just going to ignore this one
            }
        }

That’s all, most of stuff you’ll find on the web!!!

Leave a Comment