Android - Google API 和 Youtube Data v3 的问题

Android - problem with Google API and Youtube Data v3

我遇到了 Youtube API v3 的问题,特别是 Google API(简称 gapi)。 我的最终目标是调用 Youtube 数据 API videos/list 以获取有关特定视频的所有信息。

根据文档,我遵循了推荐的步骤,直到第 5 步(那里的示例有点过时)但没有成功。
Android 快速入门文档:https://developers.google.com/youtube/v3/quickstart/android

所以,我查看了他们的 API 文档,了解如何在此处撰写上述请求,并尝试使用参数部分撰写请求:“snippet”和 id:“o-YBDTqX_ZU”(或任何其他 ID)。在那里您可以看到它们的实现:取消选中 OAuth 2.0 并仅保留 API 密钥,然后执行/显示代码/Java。我试图根据我的需要重新调整他们的代码。
https://developers.google.com/youtube/v3/docs/videos/list?hl=en
https://developers.google.com/explorer-help/guides/code_samples#java

这是我的应用级别 build.gradle

plugins {
  id 'com.android.application'
  id 'kotlin-android'
}

android {
  compileSdk 30

  defaultConfig {
    applicationId "com.example.testyoutubeapi"
    minSdk 23
    targetSdk 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  kotlinOptions {
    jvmTarget = '1.8'
  }
}

dependencies {

  implementation 'androidx.core:core-ktx:1.6.0'
  implementation 'androidx.appcompat:appcompat:1.3.1'
  implementation 'com.google.android.material:material:1.4.0'
  implementation 'androidx.constraintlayout:constraintlayout:2.1.0'

  implementation 'com.google.android.gms:play-services-auth:19.2.0'
  implementation 'pub.devrel:easypermissions:0.3.0'

  implementation 'com.google.api-client:google-api-client:1.23.0'
  implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
  implementation 'com.google.apis:google-api-services-youtube:v3-rev192-1.23.0'
  implementation 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient'

  implementation 'com.google.apis:google-api-services-tasks:v1-rev48-1.23.0' exclude module: 'httpclient'
  implementation 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient'

  testImplementation 'junit:junit:4.13.2'

  androidTestImplementation 'androidx.test.ext:junit:1.1.3'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}

这是我的 YoutubeAPIclass

class YoutubeAPI() {

    companion object {
        const val DEVELOPER_KEY = "AIzaS......" // API key
        const val APPLICATION_NAME = "API code samples"
        private val JSON_FACTORY: JsonFactory = JacksonFactory.getDefaultInstance()
    }

    private fun getService(): YouTube {
        val httpTransport: HttpTransport = AndroidHttp.newCompatibleTransport() //GoogleNetHttpTransport.newTrustedTransport();
        return YouTube.Builder(httpTransport, JSON_FACTORY, null)
            .setApplicationName(APPLICATION_NAME)
            .build();
    }

    fun start(): VideoListResponse {
        val youtubeService = getService()
        val request: YouTube.Videos.List = youtubeService.videos()
            .list("snippet")
            .setKey(DEVELOPER_KEY)
            .setId("o-YBDTqX_ZU")

        return request.execute()
    }
}

这里调用AuthorizationCodeInstalledApp(flow, LocalServerReceiver()).authorize("user")时报错,提示操作不被允许

E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.testyoutubeapi, PID: 2209
    java.net.SocketException: socket failed: EPERM (Operation not permitted)
        at java.net.Socket.createImpl(Socket.java:492)
        at java.net.Socket.getImpl(Socket.java:552)
        at java.net.Socket.setSoTimeout(Socket.java:1180)
        at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
        at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:104)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at com.example.testyoutubeapi.YoutubeAPI.start(YoutubeAPI.kt:47)
        at com.example.testyoutubeapi.MainActivity.onCreate$lambda-1$lambda-0(MainActivity.kt:23)
        at com.example.testyoutubeapi.MainActivity.$r8$lambdaAdxmbUe_rlaFrgzSeLUApTyS2A(Unknown Source:0)
        at com.example.testyoutubeapi.MainActivity$$ExternalSyntheticLambda1.run(Unknown Source:4)
        at java.lang.Thread.run(Thread.java:919)

这里的问题是 Google 在 90 天不活动后禁用 api 调用。 也许创建一个每 X 天触发一次的请求(或让您的后端开发人员执行此操作)。

如果不是这样,这是一个与权限相关的问题。请务必在您的清单文件中拥有以下权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

然后,只需在模拟器上卸载应用程序,然后

  • 构建 -> 清理项目
  • 构建 -> 重建项目
  • 文件 -> 使缓存无效/重新启动

运行 再次使用您的应用,它应该可以正常工作!