Upload videos to Youtube from my web server in Java

前端 未结 2 1431
时光取名叫无心
时光取名叫无心 2021-02-10 13:49

My goal is to upload videos that are uploaded to my web server to Youtube on my own channel, not the users\' Youtube account (my web server is

2条回答
  •  灰色年华
    2021-02-10 14:35

    In general, starting at API V3, Google prefers OAuth2 over other mechanism, and uploading a video (or any other action that modifies user data) requires OAuth2.

    Fortunately, there is a special kind of token called refresh token to the rescue. Refresh token does not expire like normal access token, and is used to generate normal access token when needed. So, I divided my application into 2 parts:

    • The 1st part is for generating refresh token, which is a Java desktop app, meant to be run by a user on a computer. See here for sample code from Google.
    • The 2nd part is is part of my web application, which uses a given refresh token to create a credential object.

    Here is my implementation in Scala, which you can adapt to Java version easily:

    For generating a refresh token, you should set the accessType to offline for the authorization flow. Note: if a token already exists on your system, it won't try to get new token, even if it does not have refresh token, so you also have to set approval prompt to force:

    def authorize(dataStoreName: String, clientId: String, clientSecret: String): Credential = {
    
        val builder = new GoogleAuthorizationCodeFlow.Builder(
          HTTP_TRANSPORT,
          JSON_FACTORY,
          clientId,
          clientSecret,
          Seq(YouTubeScopes.YOUTUBE_UPLOAD)
        )
    
        val CREDENTIAL_DIRECTORY = s"${System.getProperty("user.home")}/.oauth-credentials"
        val fileDataStoreFactory = new FileDataStoreFactory(new java.io.File(CREDENTIAL_DIRECTORY))
        val dataStore: DataStore[StoredCredential] = fileDataStoreFactory.getDataStore(dataStoreName)
    
        builder.setCredentialDataStore(dataStore).setAccessType("offline").setApprovalPrompt("force")
    
        val flow = builder.build()
    
        val localReceiver = new LocalServerReceiver.Builder().setPort(8000).build()
    
        new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user")
    }
    
    val credential = authorize(dataStore, clientId, clientSecret)
    val refreshToken = credential.getRefreshToken
    

    For using the refresh token on the server, you can build a credential from a refresh token:

    def getCredential = new GoogleCredential.Builder()
        .setJsonFactory(JSON_FACTORY)
        .setTransport(HTTP_TRANSPORT)
        .setClientSecrets(clientId, clientSecret)
        .build()
        .setRefreshToken(refreshToken)
    

提交回复
热议问题