Code for download video from Youtube on Java, Android

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

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?

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Vector;  import android.app.Activity; import android.app.ProgressDialog; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.MediaController; import android.widget.VideoView;  public class MyActivity extends Activity {      private class ReceivingDataFromYoutube extends AsyncTask {          private ProgressDialog dialog = new ProgressDialog(MyActivity.this);         private String result;          protected void onPreExecute() {             dialog.setMessage("Downloading...");             dialog.show();         }          @Override         protected Void doInBackground(String... arg0) {             int begin, end;             String tmpstr = null;             try {                 URL url=new URL("http://www.youtube.com/watch?v=y12-1miZHLs&nomobile=1");                 HttpURLConnection con = (HttpURLConnection) url.openConnection();                 con.setRequestMethod("GET");                 InputStream stream=con.getInputStream();                 InputStreamReader reader=new InputStreamReader(stream);                 StringBuffer buffer=new StringBuffer();                 char[] buf=new char[262144];                                 int chars_read;                 while ((chars_read = reader.read(buf, 0, 262144)) != -1) {                     buffer.append(buf, 0, chars_read);                 }                 tmpstr=buffer.toString();                  begin  = tmpstr.indexOf("url_encoded_fmt_stream_map=");                 end = tmpstr.indexOf("&", begin + 27);                 if (end == -1) {                     end = tmpstr.indexOf("\"", begin + 27);                 }                 tmpstr = UtilClass.URLDecode(tmpstr.substring(begin + 27, end));              } catch (MalformedURLException e) {                 throw new RuntimeException();             } catch (IOException e) {                 throw new RuntimeException();             }              Vector url_encoded_fmt_stream_map = new Vector();             begin = 0;             end   = tmpstr.indexOf(",");              while (end != -1) {                 url_encoded_fmt_stream_map.addElement(tmpstr.substring(begin, end));                 begin = end + 1;                 end   = tmpstr.indexOf(",", begin);             }              url_encoded_fmt_stream_map.addElement(tmpstr.substring(begin, tmpstr.length()));             String result = "";             Enumeration url_encoded_fmt_stream_map_enum = url_encoded_fmt_stream_map.elements();             while (url_encoded_fmt_stream_map_enum.hasMoreElements()) {                 tmpstr = (String)url_encoded_fmt_stream_map_enum.nextElement();                 begin = tmpstr.indexOf("itag=");                 if (begin != -1) {                     end = tmpstr.indexOf("&", begin + 5);                      if (end == -1) {                           end = tmpstr.length();                     }                      int fmt = Integer.parseInt(tmpstr.substring(begin + 5, end));                      if (fmt == 35) {                         begin = tmpstr.indexOf("url=");                         if (begin != -1) {                             end = tmpstr.indexOf("&", begin + 4);                             if (end == -1) {                                end = tmpstr.length();                             }                             result = UtilClass.URLDecode(tmpstr.substring(begin + 4, end));                             this.result=result;                             break;                         }                     }                 }             }                      try {               URL u = new URL(result);               HttpURLConnection c = (HttpURLConnection) u.openConnection();               c.setRequestMethod("GET"); /*              c.setRequestProperty("Youtubedl-no-compression", "True");               c.setRequestProperty("User-Agent", "YouTube");*/                c.setDoOutput(true);               c.connect();                FileOutputStream f=new FileOutputStream(new File("/sdcard/3.flv"));                InputStream in=c.getInputStream();               byte[] buffer=new byte[1024];               int sz = 0;               while ( (sz = in.read(buffer)) > 0 ) {                    f.write(buffer,0, sz);               }               f.close();             } catch (MalformedURLException e) {                 new RuntimeException();             } catch (IOException e) {                 new RuntimeException();             }             return null;         }          protected void onPostExecute(Void unused) {             dialog.dismiss();         }          }       @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);          new ReceivingDataFromYoutube().execute();     }    }   

回答1:

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!!!



回答2:

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {         repositories {             maven { url "https://jitpack.io" }         }     } 

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0' 

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {      private static final String YOUTUBE_ID = "ea4-5mrpGfE";      private final YouTubeExtractor mExtractor = YouTubeExtractor.create();       private Callback mExtractionCallback = new Callback() {         @Override         public void onResponse(Call call, Response response) {             bindVideoResult(response.body());         }          @Override         public void onFailure(Call call, Throwable t) {             onError(t);         }     };       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);   //        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'         mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);      }       private void onError(Throwable t) {         t.printStackTrace();         Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();     }       private void bindVideoResult(YouTubeExtractionResult result) {  //        Here you can get download url link         Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());          Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();     } } 

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {     maven { url "https://jitpack.io" } }  compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT' 

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";      YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {         @Override         public void onUrisAvailable(String videoId, String videoTitle, SparseArray ytFiles) {             if (ytFiles != null) {                 int itag = 22; // Here you can get download url                 String downloadUrl = ytFiles.get(itag).getUrl();             }         }     };      ytEx.execute(youtubeLink); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!