Code for download video from Youtube on Java, Android

前端 未结 3 916
难免孤独
难免孤独 2020-11-30 17:19

I created code for download video from Youtube, but this code doesn\'t work with Wi-fi connection and work with mobile connection. Where did I have mistake?

         


        
3条回答
  •  感情败类
    2020-11-30 17:57

    3 steps:

    1. Check the sorce 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: http://www.w3schools.com/tags/ref_urlencode.asp 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!!!

提交回复
热议问题