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

时间:2014-09-08 06:11:01

标签: java video youtube

6 个答案:

答案 0 :(得分:13)

以下代码将提取以下类型网址的视频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();
        }

答案 1 :(得分:4)

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

enter image description here

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

连接到80端口上的youtube.be并将其写入输出流:

GET /6UW3xuJinEg HTTP/1.1



# Don't forget the blank lines

答案 2 :(得分:1)

我为此找到了解决方案..我扩展了该网址..及其工作..

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

答案 3 :(得分:0)

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

使用此方法,它在大多数情况下都可以在上述答案中返回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

答案 4 :(得分:0)

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

 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://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>

答案 5 :(得分:-1)

在此处尝试此代码。

// (?: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;
}

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

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