2013-05-23 2 views
1

Как получить токен обновления и токен доступа с первого кода авторизации? И как я могу повторно использовать этот токен обновления, чтобы получить новый токен доступа для загрузки на Google Диск с помощью Java API? Это не веб-приложение. Это код Java Swing.Обновить токен и повторно использовать этот токен, чтобы получить новый токен доступа java

ответ

0

Вот решение, которое я недавно составил от основного примера в документации Google Drive и некоторые экспериментирования: IApiKey содержит статические строки CLIENT_ID, и так далее. ITokenPersistence - это интерфейс, который позволяет загружать и сохранять токен (как String). Он отделяет механизм сохранения (я использовал Preferences для приложения ECP Eclipse e4) от Uploader. Это может быть так же просто, как хранить токен в файле. IAthorizationManager - это интерфейс, который используется для предоставления пользователям доступа к ним и ввода кода для создания токена обновления. Я реализовал Dialog, содержащий виджет браузера, чтобы предоставить доступ, и текстовое поле для копирования и вставки кода. Специальное исключение GoogleDriveException скрывает классы API от остальной части кода.

public final class Uploader implements IApiKey { 

    public static final String TEXT_PLAIN = "text/plain"; 

    private final ITokenPersistence tokenManager; 
    private final IAuthorizationManager auth; 

    public Uploader(final ITokenPersistence tm, final IAuthorizationManager am) { 
     this.tokenManager = tm; 
     this.auth = am; 
    } 

    private GoogleCredential createCredentialWithRefreshToken(
      final HttpTransport transport, 
      final JsonFactory jsonFactory, 
      final String clientId, 
      final String clientSecret, 
      final TokenResponse tokenResponse) { 
     return new GoogleCredential.Builder().setTransport(transport) 
       .setJsonFactory(jsonFactory) 
       .setClientSecrets(clientId, clientSecret) 
       .build() 
       .setFromTokenResponse(tokenResponse); 
    } 

    /** 
    * Upload the given file to Google Drive. 
    * <P> 
    * The name in Google Drive will be the same as the file name. 
    * @param fileContent a file of type text/plain 
    * @param description a description for the file in Google Drive 
    * @return Answer the ID of the uploaded file in Google Drive. 
    *   Answer <code>null</code> if the upload failed. 
    * @throws IOException 
    * @throws {@link GoogleDriveException} when a <code>TokenResponseException</code> had been 
    *   intercepted while inserting (uploading) the file. 
    */ 
    public String upload(final java.io.File fileContent, final String description) throws IOException, GoogleDriveException { 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     // If we do not already have a refresh token a flow is created to get a refresh token. 
     // To get the token the user has to visit a web site and enter the code afterwards 
     // The refresh token is saved and may be reused. 
     final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, 
       jsonFactory, 
       CLIENT_ID, 
       CLIENT_SECRET, 
       Arrays.asList(DriveScopes.DRIVE)) 
     .setAccessType("offline") 
     .setApprovalPrompt("auto").build(); 

     final String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); 
     final String refreshToken = this.tokenManager.loadRefreshToken(); 

     GoogleCredential credential = null; 
     if(refreshToken == null) { 
      // no token available: get one 
      String code = this.auth.authorize(url); 
      GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); 
      this.tokenManager.saveRefreshToken(response.getRefreshToken()); 
      credential = this.createCredentialWithRefreshToken(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, response); 
     } 
     else { 
      // we have a token, if it is expired or revoked by the user the service call (see below) may fail 
      credential = new GoogleCredential.Builder() 
      .setJsonFactory(jsonFactory) 
      .setTransport(httpTransport) 
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET) 
      .build(); 
      credential.setRefreshToken(refreshToken); 
     } 

     //Create a new authorized API client 
     final Drive service = new Drive.Builder(httpTransport, jsonFactory, credential) 
     .setApplicationName(APP_NAME) 
     .build(); 

     //Insert a file 
     final File body = new File(); 
     body.setTitle(fileContent.getName()); 
     body.setDescription(description); 
     body.setMimeType(TEXT_PLAIN); 
     final FileContent mediaContent = new FileContent(TEXT_PLAIN, fileContent); 

     try { 
      final File file = service.files().insert(body, mediaContent).execute(); 
      return (file != null) ? file.getId() : null; 
     } catch (TokenResponseException e) { 
      e.printStackTrace(); 
      throw new GoogleDriveException(e.getDetails().getErrorDescription(), e.getCause()); 
     } 
    } 

}

1

Мы можем повторно использовать маркер обновления, чтобы получить новый маркер доступа, следующий код

public class OAuthRefreshToken implements CredentialRefreshListener { 

    public static GoogleCredential getAccessTokenFromRefreshToken(String refreshToken, HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, String CLIENT_ID, String CLIENT_SECRET) throws IOException 
    { 
     GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder() 
     .setTransport(transport).setJsonFactory(jsonFactory) 
     .setClientSecrets(CLIENT_ID, CLIENT_SECRET); 
     credentialBuilder.addRefreshListener(new OAuthRefreshToken()); 

     GoogleCredential credential = credentialBuilder.build(); 
     credential.setRefreshToken(refreshToken); 
     credential.refreshToken(); 
     return credential; 
    } 

    @Override 
    public void onTokenErrorResponse(Credential arg0, TokenErrorResponse arg1) 
      throws IOException { 
     // TODO Auto-generated method stub 
     System.out.println("Error occured !"); 
     System.out.println(arg1.getError()); 
    } 

    @Override 
    public void onTokenResponse(Credential arg0, TokenResponse arg1) 
      throws IOException { 
     // TODO Auto-generated method stub 
     System.out.println(arg0.getAccessToken()); 
     System.out.println(arg0.getRefreshToken()); 
    } 

} 
Смежные вопросы