如何通过YouTube API获取YouTube视频的标题

时间:2017-07-06 06:30:56

标签: java android youtube youtube-api android-youtube-api

我有YouTube视频的布局。我想设置视频的缩略图和标题。 (我成功设置了缩略图而不是标题)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1.0">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:layout_marginTop="10dp"
        android:id="@+id/youtubeThumbnailView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="YouTube Video"
        android:textSize="20sp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:id="@+id/textViewTitle"/>
</LinearLayout>

我在这里设置缩略图:

YouTubeThumbnailView youTubeThumbnailView = (YouTubeThumbnailView) newChild.findViewById(R.id.youtubeThumbnailView);
youTubeThumbnailView.initialize(YouTubePlayer.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
    @Override
    public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {   
        youTubeThumbnailLoader.setVideo("FM7MFYoylVs");
        youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
             @Override
             public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                  youTubeThumbnailLoader.release();
             }

             @Override
             public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
             }
        });
    }

    @Override
    public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
    }
});

如何从视频中获取标题?

我在这里看到了一个解决方案:Get title of YouTube video

但我不确定这是否正确。我想YouTube API可让我们以更简单的方式获取标题,例如:youTubeThumbnailView.getText()。

4 个答案:

答案 0 :(得分:1)

来自youtube的Json数据是:

{...
 "items": [
  {
   "kind": "youtube#video",
   "etag": ".....",
   "id": "....",
   "snippet": {
    "publishedAt": ".....",
    "channelId": "...",
    "title": "This is the title",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://....jpg",
      "width": 120,
      "height": 90
....

获得标题:

JsonArray items = jsondata.getAsJsonArray("items");
JsonObject snippet = item.getAsJsonObject("snippet");
String title = snippet.get("title").getAsString();

我建议使用https://github.com/koush/ion加载数据。

答案 1 :(得分:1)

var agents = new List<Agent>();
                string response = message.Content.ReadAsStringAsync().Result;
                var account = JsonConvert.DeserializeObject<RootObject>(response);
                var list = new List<Daily>();

                foreach (Agent agent in account.Account.Agents)
                {
                    agents.Add(agent);
                }

                for (int i = 0; i < agents.Count; i++)
                {
                    list[i].Date = agents[i].PoliciesInForce.Daily[i].Date;
                    list[i].PifCnt = agents[i].PoliciesInForce.Daily[i].PifCnt;
                    list[i].NoPopPifCnt = agents[i].PoliciesInForce.Daily[i].NoPopPifCnt;
                    list[i].PopPifCnt = agents[i].PoliciesInForce.Daily[i].PopPifCnt;
                    list[i].CleanPopPifCount = agents[i].PoliciesInForce.Daily[i].CleanPopPifCount;
                }

答案 2 :(得分:1)

您可以使用google api获取它:https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=YOUR_VIDEO_ID&key=KEY

答案 3 :(得分:1)

我喜欢使用 https://www.youtube.com/get_video_info 来实现这一点。快速响应也会为您提供许多额外有用的信息。它采用查询字符串格式,并有一个参数“player_response”,它是一个 JSON 对象,其中包含您可能需要的有关视频的每条信息。

private static final Pattern YOUTUBE_ID_PATTERN = Pattern.compile("(?<=v\\=|youtu\\.be\\/)\\w+");
private static final Gson GSON = new GsonBuilder().create();

public static String getYouTubeTitle(String url) {
    Matcher m = YOUTUBE_ID_PATTERN.matcher(url);
    if (!m.find())
        throw new IllegalArgumentException("Invalid YouTube URL.");
    JsonElement element = getYoutubeInfo(m.group());
    // The "videoDetails" object contains the video title
    return element.getAsJsonObject().get("videoDetails").getAsJsonObject().get("title").getAsJsonPrimitive().getAsString();
}

public static JsonElement getYoutubeInfo(String youtubeID) throws MalformedURLException, IOException {
    String url = "https://www.youtube.com/get_video_info?video_id=" + youtubeID;
    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
    connection.addRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36");
    connection.connect();

    String content = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); // Apache commons. Use whatever you like 
    connection.disconnect();

    String[] queryParams = content.split("\\&"); // It's query string format, so split on ampterstands
    for (String param : queryParams) {
        param = URLDecoder.decode(param, StandardCharsets.UTF_8.name()); // It's encoded, so decode it
        String[] parts = param.split("\\=", 2); // Again, query string format. Split on the first equals character
        if (parts[0].equalsIgnoreCase("player_response")) // We want the player_response parameter. This has all the info
            return GSON.fromJson(parts[1], JsonElement.class); // It's in JSON format, so you use a JSON deserializer to deserialize it
    }

    throw new RuntimeException("Failed to get info for video: " + youtubeID);
}