eos1d3
eos1d3

Reputation: 423

Access token is always expired in 1 hour with YouTube API V3 for Java

I am able to use the sample Java program to upload video to YouTube using API V3.

However, the access token generated by oAuth2 will always be expired after one hour. How to refresh the access token with the Java library so that it is never expired?

Java Version of YouTube Upload Sample Program

Upvotes: 1

Views: 1862

Answers (2)

eos1d3
eos1d3

Reputation: 423

Finally found a Java fix for YouTube API V3. In original sample Java program, changes are need in Auth.java. Original is:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
        .build();

And we need to add two more things:

  1. setAccessType("offline")
  2. setApprovalPrompt("force")

So this works now to get refresh token.

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setAccessType("offline").setApprovalPrompt("force").setCredentialDataStore(datastore)
        .build();

Now credential.getRefreshToken() will return a token instead of null. And credential.refreshToken() will return true instead of false.

Upvotes: 1

JohnB
JohnB

Reputation: 59

I had the same thing to do (but with c# .net). With the API I did not be able to get a refresh token.

So I used an HTTPClient to request Youtube API through HTTP API :

  1. On request to redirect the user to Google OAuth server
  2. Google OAuth server return a code
  3. You send a POST to Google OAuth with this code
  4. Google OAuth server give you an access_token and a refresh_token

At this point I have a refresh and an access token for the user. After this, I use the API to refresh the token (if needed) and make request to Youtube.

I recommend Google Playground to help you making your HTTP requests.

Upvotes: 0

Related Questions