java 如何使用java从URL获取youtube视频ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25718304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:31:45  来源:igfitidea点击:

How to get youtube video id from URL with java?

javavideoyoutube

提问by Er KK Chopra

I want to get the v=id from youtube's URL with java

我想用 java 从 youtube 的 URL 中获取 v=id

Example Youtube URL formats:

Youtube URL 格式示例:

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfWhttp://www.youtube.com/watch?v=u8nQa1cJyX8http://youtu.be/0zM3nApSvMghttp://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQhttp://youtu.be/dQw4w9WgXcQhttp://www.youtube.com/embed/dQw4w9WgXcQhttp://www.youtube.com/v/dQw4w9WgXcQhttp://www.youtube.com/e/dQw4w9WgXcQhttp://www.youtube.com/watch?v=dQw4w9WgXcQhttp://www.youtube.com/?v=dQw4w9WgXcQhttp://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQhttp://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQhttp://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQhttp://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW http://www.youtube.com/watch?v=u8nQa1cJyX8 http://youtu.be/0zM3nApSvMg http://www.youtube.com /user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ http://youtu.be/dQw4w9WgXcQ http://www.youtube.com/embed/dQw4w9WgXcQ http://www.youtube.com/v/dQw4w9WgXcQ http ://www.youtube.com/e/dQw4w9WgXcQ http://www.youtube.com/watch?v=dQw4w9WgXcQ http://www.youtube.com/?v=dQw4w9WgXcQ http://www.youtube.com /watch?feature=player_embedded&v=dQw4w9WgXcQ http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQhttp://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

or any other youtube format what contains a video id in the url

或任何其他在 url 中包含视频 ID 的 youtube 格式

I am Trying with that :-

我正在尝试:-

  Pattern compiledPattern = Pattern.compile("(?<=v=).*?(?=&|$)",Pattern.CASE_INSENSITIVE);      
        Matcher matcher = compiledPattern.matcher(sourceUrl);
        if(matcher.find()){
            setVideoId(matcher.group());
        }

It is not working only for one URL :-

它不仅适用于一个 URL :-

http://youtu.be/6UW3xuJinEg

http://youtu.be/6UW3xuJinEg

采纳答案by Er KK Chopra

I found solution for this .. i expand that URL.. and its working ..

我找到了解决方案..我扩展了那个 URL.. 和它的工作..

public static String expandUrl(String shortenedUrl)  {
        URL url;
        String expandedURL = "";
        try {
            url = new URL(shortenedUrl);
            // open connection
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); 
            // stop following browser redirect
            httpURLConnection.setInstanceFollowRedirects(false);
            // extract location header containing the actual destination URL
            expandedURL = httpURLConnection.getHeaderField("Location");
            httpURLConnection.disconnect();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
         return expandedURL;
    }

回答by Jakki

The code below will extract the video ids for the following type of urls.

下面的代码将提取以下类型的 url 的视频 ID。

http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/watch?v=dQw4w9WgXcQ 
http://youtu.be/dQw4w9WgXcQ 
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ 
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

String pattern = "(?<=watch\?v=|/videos/|embed\/|youtu.be\/|\/v\/|\/e\/|watch\?v%3D|watch\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\&\?\n]*";

        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(url); //url is youtube url for which you want to extract the id.
        if (matcher.find()) {
             return matcher.group();
        }

回答by Mohammad Jafar Mashhadi

6UW3xuJinEg(i mean the string after youtu.be/) is the ID most of the time. But for being more sure you can send HTTP GET request to that URL and it will respond you with a HTTP302 redirect response where you can find the actual redirection URL. you can parse that URL your previous code.

6UW3xuJinEg(我的意思是youtu.be/)之后的字符串在大多数情况下是 ID。但是为了更确定您可以向该 URL 发送 HTTP GET 请求,它会以 HTTP302 重定向响应响应您,您可以在其中找到实际的重定向 URL。您可以解析该 URL 您以前的代码。

enter image description here

在此处输入图片说明

To send and recieve that request and response you can use libraries like jsoup. but because it's just a simple GET request you can simply use java sockets.

要发送和接收该请求和响应,您可以使用像 jsoup 这样的库。但是因为它只是一个简单的 GET 请求,所以您可以简单地使用 java 套接字。

Connect to youtube.beon 80 port and write this in output stream:

连接到youtube.be80 端口并将其写入输出流:

GET /6UW3xuJinEg HTTP/1.1



# Don't forget the blank lines

回答by Kyo Huu

private String getYouTubeId(String youTubeUrl) {
        String pattern = "https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:['\"][^<>]*>|</a>))[?=&+%\w]*";

        Pattern compiledPattern = Pattern.compile(pattern,
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = compiledPattern.matcher(youTubeUrl);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
}

Use this method, it works in most case that return Null in above answers. cases tested:

使用此方法,它在大多数情况下都有效,在上述答案中返回 Null。测试案例:

https://m.youtube.com/watch?feature=youtu.be&v=ROkXM3csNWY
https://www.youtube.com/watch?v=rie69P0W668
https://m.youtube.com/watch?feature=youtu.be&v=JqyzwbpYYqc
https://www.youtube.com/watch?v=YPln3JP_gKs&feature=youtu.be

回答by Alex Smith

You can use regex I've created:

您可以使用我创建的正则表达式:

 public static String  YOUTUBE_PATTERN_ID = "^(?:(?:\w*.?://)?\w*.?\w*-?.?\w*/(?:embed|e|v|watch|.*/)?\??(?:feature=\w*\.?\w*)?&?(?:v=)?/?)([\w\d_-]+).*";

Pattern matcher = Pattern.compile(YOUTUBE_PATTERN_ID).matcher(url)
  if (matcher.find()) {
        return matcher.group(1)
  }

https://regex101.com/r/b0yMMd/1

https://regex101.com/r/b0yMMd/1

Used snippet base from this answer: https://stackoverflow.com/a/35436389/7138308

使用此答案中的片段库:https: //stackoverflow.com/a/35436389/7138308

var regex = /^(?:(?:\w*.?:\/\/)?\w*.?\w*\-?.?\w*\/(?:embed|e|v|watch|.*\/)?\??(?:feature=\w*\.?\w*)?\&?(?:v=)?\/?)([\w\d_-]+).*/i;

// An array of all the youtube URLs
var youtubeLinks = [
    'http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW ',
    'http://www.youtube.com/watch?v=u8nQa1cJyX-8  ',
    'http://youtu.be/0zM3nApSvMg ',
    'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ  ',
    'http://youtu.be/dQw4w9WgXcQ  ',
    'http://www.youtube.com/embed/dQw4w9WgXcQ  ',
    'http://www.youtube.com/v/dQw4w9WgXcQ  ',
    'http://www.youtube.com/e/dQw4w9WgXcQ  ',
    'http://www.youtube.com/watch?v=dQw4w9WgXcQ  ',
    'http://www.youtube.com/?v=dQw4w9WgXcQ  ',
    'http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ  ',
    'http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ  ',
    'http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ  ',
    'http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0 ',
    'https://m.youtube.com/watch?feature=youtu.be&v=ROkXM3csNWY ',
    'https://www.youtube.com/watch?v=rie69P0W668 ',
    'https://m.youtube.com/watch?feature=youtu.be&v=JqyzwbpYYqc ',
    'https://www.youtube.com/watch?v=YPln3JP_gKs&feature=youtu.be ',
    'https://www.youtube.com/watch?v=l-kX8Z4u0Kw&list=PLhml-dmiPOedRDLV8n1ro_OTdzKjOdlyp'
];

// An object to store the results
var youtubeIds = {};

// Iterate over the youtube URLs
youtubeLinks.forEach(function(url) {
    // Get the value of second captured group to extract youtube ID
    var id = "<span class='youtubeId'>" + (url.match(regex) || [0, 0, 'No ID present'])[1] + "</span>";

    // Add the URL and the extracted ID in the result object
    youtubeIds[url] = id;
});

// Log the object in the browser console
console.log(youtubeIds);

// To show the result on the page
document.getElementById('output').innerHTML = JSON.stringify(youtubeIds, 0, 4);
.youtubeId {
    color: green;
    font-weight: bold;
}
<pre id="output"></pre>

回答by The Finest Artist

Try this code here.

在这里试试这个代码。

// (?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})
final static String reg = "(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})";

public static String getVideoId(String videoUrl) {
    if (videoUrl == null || videoUrl.trim().length() <= 0)
        return null;

    Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(videoUrl);

    if (matcher.find())
        return matcher.group(1);
    return null;
}

You can find my whole parser code from here https://github.com/TheFinestArtist/YouTubePlayerActivity/blob/master/library/src/main/java/com/thefinestartist/ytpa/utils/YoutubeUrlParser.java

你可以从这里找到我的整个解析器代码 https://github.com/TheFinestArtist/YouTubePlayerActivity/blob/master/library/src/main/java/com/thefinestartist/ytpa/utils/YoutubeUrlParser.java

This is useful open source I made to play Youtube Video. https://github.com/TheFinestArtist/YouTubePlayerActivity

这是我用来播放 Youtube Video 的有用开源。 https://github.com/TheFinestArtist/YouTubePlayerActivity