2016-01-09 247 views
0
public class image { 
    private String applicationName; 

    public image setApplicationName(String applicationName) { 
      this.applicationName = applicationName; 
      return this; 
     } 
     private static String CLIENT_ID = "***"; 
     private static String CLIENT_SECRET = "***"; 
     private static String REDIRECT_URI = "https://developers.google.com/oauthplayground"; 

    public static void main(String[] args) throws IOException{ 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)) 
      .setAccessType("offline") 
      .setApprovalPrompt("auto").build(); 


     String code = "4/-4JsvGiqNpZ6Ms5dLjLA2QgzgToGAxx_SZTeByBPh_Q"; 

     GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); 

     GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) 
     .setJsonFactory(jsonFactory) 
     .setClientSecrets(CLIENT_ID, CLIENT_SECRET) 
     .build() 
     .setFromTokenResponse(response); 

     Drive service = new Drive.Builder(httpTransport, jsonFactory, null) 
     .setHttpRequestInitializer(credential) 
     .setApplicationName("musik") 
     .build(); 

     //Insert a file 
     File body = new File(); 
     body.setTitle("My document"); 
     body.setDescription("A test document"); 
     body.setMimeType("text/plain"); 

     java.io.File fileContent = new java.io.File("document.txt"); 
     FileContent mediaContent = new FileContent("text/plain", fileContent); 

     File file = service.files().insert(body, mediaContent).execute(); 
     System.out.println("File ID: " + file.getId()); 
    } 

} 

我想上傳使用硬盤API我的驅動器上的文件,每次兌換谷歌授權碼,一切工作正常,除了我每次贖回谷歌授權的代碼使用後。 上述代碼是否有任何調整或方法不能通過使用任何刷新令牌或訪問令牌方法每次兌換I?如何避免

回答

1

您無需每次兌換授權碼。您獲得授權碼,然後在通過身份驗證後刷新並訪問令牌。因此,您可以使用刷新令牌刷新訪問令牌,然後執行谷歌驅動器操作。

內容主體應該在這個格式 「CLIENT_ID = [的clientId] & client_secret = [clientSecret] & refresh_token = [RefreshToken] & grant_type = refresh_token」,並做了HTTP POST方法來刷新訪問令牌。

+0

Suhas你可以調整上面的代碼來說明這個概念嗎? –