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());
}
}
我正在尝试使用Drive Api在我的驱动器上传文件,一切正常,但我必须在每次使用后兑换Google授权代码。 是否有任何调整或方法使上述代码不能每次使用任何刷新令牌或访问令牌方法来兑换我?
答案 0 :(得分:1)
您无需每次都兑换授权码。获得授权代码,然后在进行身份验证后刷新并访问令牌。因此,您可以使用刷新令牌刷新访问令牌,然后执行谷歌驱动器操作。
内容正文应为“ client_id = [clientId]& client_secret = [clientSecret]& refresh_token = [RefreshToken]& grant_type = refresh_token ”并执行HTTP post方法刷新访问令牌。