【问题标题】:How to get the Youtube download link using java?如何使用 java 获取 Youtube 下载链接?
【发布时间】:2015-07-07 06:50:14
【问题描述】:

我知道 VGet 让下载 youtube 视频变得容易。但是,我只想获取下载链接以在我的应用程序的其余部分(Java Swing)中使用它。可以使用 VGet 完成吗?

谁能帮帮我,好吗?

谢谢。

【问题讨论】:

  • 你有什么尝试吗?显示您的代码
  • VGet git 上的 API。使用它并做你想做的事。
  • 您可以使用 youtube api 下载您的视频:developers.google.com/youtube/v3/code_samples/…
  • 正如我之前指定的,我尝试了 VGet,我能够下载一个 youtube 视频,VGet v = new VGet(new URL("youtube.com/watch?v=ID"), new File("/Users/.. ./Downloads")); v.download(); 这行得通。但是,我确实需要知道 VGet 是否提供任何功能来获取下载链接,而不是下载视频?

标签: java youtube


【解决方案1】:

这是我的解决方案,(非常感谢更好的解决方案)

参考 VGet 后,我​​编写了自己的方法来获取 youtube url(如 https:www.youtube.com/watch?v=ID)并提供下载链接(如 https:r2---sn -ipoxu-u2xl.googlevideo.com/videoplayback?upn=l0CJXtFDQog&itag=43&signature=0C6...&mt=1436339343)。这是代码,

    List<String> urlList = new ArrayList<String>();
    Pattern urlencod = Pattern.compile("\"url_encoded_fmt_stream_map\":\"([^\"]*)\"");
    Matcher urlencodMatch = urlencod.matcher(**html**);
    if (urlencodMatch.find()) {
        String url_encoded_fmt_stream_map;
        url_encoded_fmt_stream_map = urlencodMatch.group(1);
        Pattern encod = Pattern.compile("url=(.*)");
        Matcher encodMatch = encod.matcher(url_encoded_fmt_stream_map);
        if (encodMatch.find()) {
            String sline = encodMatch.group(1);
            String[] urlStrings = sline.split("url=");
            for (String urlString : urlStrings) {
                String url = null;
                urlString = StringEscapeUtils.unescapeJava(urlString);
                Pattern link = Pattern.compile("([^&,]*)[&,]");
                Matcher linkMatch = link.matcher(urlString);
                if (linkMatch.find()) {
                    url = linkMatch.group(1);
                    url = URLDecoder.decode(url, UTF8);
                }
                urlList.add(url);
            }
        }
    }

其中,html 是使用的字符串,

    HttpURLConnection conn = null;
    StringBuilder contents = new StringBuilder();
    try {
        conn = (HttpURLConnection)new URL("https://www.youtube.com/watch?v=SYOarZKipnU").openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);

        InputStream is = conn.getInputStream();

        String enc = conn.getContentEncoding();

        if (enc == null) {
            Pattern p = Pattern.compile("charset=(.*)");
            Matcher m = p.matcher(conn.getHeaderField("Content-Type"));
            if (m.find()) {
                enc = m.group(1);
            }
        }

        if (enc == null)
            enc = "UTF-8";

        BufferedReader br = new BufferedReader(new InputStreamReader(is, enc));

        String line = null;


        while ((line = br.readLine()) != null) {
            contents.append(line);
            contents.append("\n");

        }
    }catch(IOException e){

    }

            return contents.toString();
        }

谢谢你们……

【讨论】:

  • 嗨 Moni,为什么这里有多个 url?我应该使用哪一个来下载?
【解决方案2】:

我找到的最简单的解决方案如下, YouTube 视频的 HTML 页面中包含文件的 URL。

在该页面上搜索类似于 'url=https%3A%2F%2Fr12---sn-5hne6nse.googlevideo.com%2' 的代码

这不是完整的 URL,但它指向特定分辨率的一个条目。对于从可用的最高可用分辨率开始的每个可用分辨率,都会重复此代码。我做了一些测试,发现播放文件所需的最小 URL 如下

所以如果你想要 720p 版本,那么,

我发现'quality=hd720\'和'ratebypass%3Dyes'之间包含的代码如果粘贴到浏览器中会播放所需的文件,所以如果你再使用,

字符串结果 = str.substring(str.indexOf("quality=hd720"), str.indexOf("ratebypass%3Dyes"));

假设有可用的 720 将提取播放文件所需的 URL。

使用 Uri.decode(url) 解码 URL 以删除那些 %codes

嘿,很快,在 Java 中用作 URL 的内容将下载该文件。

【讨论】:

    【解决方案3】:

    来自https://github.com/axet/vget

    package com.github.axet.vget;
    
    import java.io.File;
    import java.net.URL;
    
    public class DirectDownload {
    
        public static void main(String[] args) {
            try {
                // ex: http://www.youtube.com/watch?v=Nj6PFaDmp6c
                String url = args[0];
                // ex: "/Users/axet/Downloads"
                String path = args[1];
                VGet v = new VGet(new URL(url), new File(path));
                v.download();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    

    还有来自https://github.com/axet/vget

    import java.io.File;
    import java.net.URL;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    import com.github.axet.vget.info.VGetParser;
    import com.github.axet.vget.info.VideoInfo;
    import com.github.axet.vget.vhs.VimeoInfo;
    import com.github.axet.vget.vhs.YoutubeInfo;
    import com.github.axet.wget.info.DownloadInfo;
    import com.github.axet.wget.info.DownloadInfo.Part;
    import com.github.axet.wget.info.DownloadInfo.Part.States;
    
    public class AppManagedDownload {
    
        VideoInfo info;
        long last;
    
        public void run(String url, File path) {
            try {
                AtomicBoolean stop = new AtomicBoolean(false);
                Runnable notify = new Runnable() {
                    @Override
                    public void run() {
                        VideoInfo i1 = info;
                        DownloadInfo i2 = i1.getInfo();
    
                        // notify app or save download state
                        // you can extract information from DownloadInfo info;
                        switch (i1.getState()) {
                        case EXTRACTING:
                        case EXTRACTING_DONE:
                        case DONE:
                            if (i1 instanceof YoutubeInfo) {
                                YoutubeInfo i = (YoutubeInfo) i1;
                                System.out.println(i1.getState() + " " + i.getVideoQuality());
                            } else if (i1 instanceof VimeoInfo) {
                                VimeoInfo i = (VimeoInfo) i1;
                                System.out.println(i1.getState() + " " + i.getVideoQuality());
                            } else {
                                System.out.println("downloading unknown quality");
                            }
                            break;
                        case RETRYING:
                            System.out.println(i1.getState() + " " + i1.getDelay());
                            break;
                        case DOWNLOADING:
                            long now = System.currentTimeMillis();
                            if (now - 1000 > last) {
                                last = now;
    
                                String parts = "";
    
                                List<Part> pp = i2.getParts();
                                if (pp != null) {
                                    // multipart download
                                    for (Part p : pp) {
                                        if (p.getState().equals(States.DOWNLOADING)) {
                                            parts += String.format("Part#%d(%.2f) ", p.getNumber(), p.getCount()
                                                    / (float) p.getLength());
                                        }
                                    }
                                }
    
                                System.out.println(String.format("%s %.2f %s", i1.getState(),
                                        i2.getCount() / (float) i2.getLength(), parts));
                            }
                            break;
                        default:
                            break;
                        }
                    }
                };
    
                URL web = new URL(url);
    
                // [OPTIONAL] limit maximum quality, or do not call this function if
                // you wish maximum quality available.
                //
                // if youtube does not have video with requested quality, program
                // will raise en exception.
                VGetParser user = null;
    
                // create proper html parser depends on url
                user = VGet.parser(web);
    
                // download maximum video quality from youtube
                // user = new YouTubeQParser(YoutubeQuality.p480);
    
                // download mp4 format only, fail if non exist
                // user = new YouTubeMPGParser();
    
                // create proper videoinfo to keep specific video information
                info = user.info(web);
    
                VGet v = new VGet(info, path);
    
                // [OPTIONAL] call v.extract() only if you d like to get video title
                // or download url link
                // before start download. or just skip it.
                v.extract(user, stop, notify);
    
                System.out.println("Title: " + info.getTitle());
                System.out.println("Download URL: " + info.getInfo().getSource());
    
                v.download(user, stop, notify);
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        public static void main(String[] args) {
            AppManagedDownload e = new AppManagedDownload();
            // ex: http://www.youtube.com/watch?v=Nj6PFaDmp6c
            String url = args[0];
            // ex: /Users/axet/Downloads/
            String path = args[1];
            e.run(url, new File(path));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2014-10-20
      相关资源
      最近更新 更多