Moni
Moni

Reputation: 131

How to get the Youtube download link using java?

I know that downloading a youtube video is made easy by VGet. But, i just want to get the download link to use it in rest of my application (Java Swing) . Can it be done using VGet?

Can anyone help me, Please.?

Thank you.

Upvotes: 1

Views: 10270

Answers (3)

JackDaw
JackDaw

Reputation: 21

The easiest solution I found is as follows, Contained in the HTML page of the YouTube video is the URL of the file.

Search that page for a code looking something like 'url=https%3A%2F%2Fr12---sn-5hne6nse.googlevideo.com%2'

This is not the complete URL but it points to one entry of a certain resolution. This code is repeated for every resolution available starting with the highest available. I did some testing and found the minimum URL required to get the file to play as follows

so if you want the 720p version then,

I found the code contained between 'quality=hd720\' and 'ratebypass%3Dyes' if pasted into a browser plays the required file so if you then use,

String result = str.substring(str.indexOf("quality=hd720"), str.indexOf("ratebypass%3Dyes"));

assuming there is a 720 available will pull out the URL needed to play the file.

Decode the URL using Uri.decode(url) to remove those %codes

and hey presto, whats left used as a URL in Java will download the file.

Upvotes: 1

Moni
Moni

Reputation: 131

Here's my solution, (Better solution much appreciated)

After refering to VGet , i wrote my own method to get the youtube url( like, https:www.youtube.com/watch?v=ID) and give the download link (like, https:r2---sn-ipoxu-u2xl.googlevideo.com/videoplayback?upn=l0CJXtFDQog&itag=43&signature=0C6...&mt=1436339343). Here's the code ,

    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);
            }
        }
    }

where, html is the String got using ,

    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();
        }

Thank you guyzz....

Upvotes: 1

Danielson
Danielson

Reputation: 2696

From 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);
        }
    }

}

And also from 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));
    }
}

Upvotes: 0

Related Questions