【发布时间】:2021-10-12 14:15:52
【问题描述】:
我正在开发一个需要将文件上传到 Google Drive 帐户的 spring-boot 应用程序。我找到了一个用于存储 access_token 和刷新令牌的线程,但已被弃用,这里是链接:How to store credentials for Google Drive SDK locally。 有没有办法使用 v3 实现一次 google drive 身份验证,并在需要时刷新访问令牌?
以下是上传文件到驱动器的服务
@Service
public class GoogleDriveService {
private static final String baseConfigPath = "/config.json";
private static final String APPLICATION_NAME = "application name";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/client_secret.json";
/////////////////////////////////////////////////////////////////////////////////////////
public static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = GoogleDriveClient.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost("127.0.0.1").setPort(8089).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public boolean uploadGoogleDriveFile(java.io.File originalFile){
final NetHttpTransport HTTP_TRANSPORT;
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
File file = new File();
file.setName(originalFile.getName());
FileContent content = new FileContent("text/plain", originalFile);
File uploadedFile = service.files().create(file, content).setFields("id").execute();
System.out.println("File ID: " + uploadedFile.getId());
return true;
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
return false;
}
}
}
【问题讨论】:
标签: java spring-boot google-drive-api google-api-java-client