【发布时间】:2019-07-20 21:46:37
【问题描述】:
这是我正在使用我的驱动器启用文件“credentials.json”进行项目 OAuth 2.0 身份验证的当前代码,这对本地项目工作正常,当我要实施这个项目时停止工作。
public class GoogleDriveUtils {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
// Directory to store user credentials for this application.
private static final java.io.File CREDENTIALS_FOLDER //
= new java.io.File("/tmp/");
private static final String CLIENT_SECRET_FILE_NAME = "credentials.json";
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
// Global instance of the {@link FileDataStoreFactory}.
private static FileDataStoreFactory DATA_STORE_FACTORY;
// Global instance of the HTTP transport.
private static HttpTransport HTTP_TRANSPORT;
private static Drive _driveService;
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(CREDENTIALS_FOLDER);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
public static Credential getCredentials() throws IOException {
java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
if (!clientSecretFilePath.exists()) {
throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
+ " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
}
InputStream in = new FileInputStream(clientSecretFilePath);
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(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
public static Drive getDriveService() throws IOException {
if (_driveService != null) {
return _driveService;
}
Credential credential = getCredentials();
//
_driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
.setApplicationName(APPLICATION_NAME).build();
return _driveService;
}
}
【问题讨论】:
-
请定义停止工作在托管之前它是否有效?究竟是什么不工作?你在哪里托管它?
-
是的,它在托管之前工作,我认为这是因为重定向 url 就像在生成凭据时没有指定 URL 之前一样,它需要 'localhost://**** *' - 当我指定我的托管网址时,例如www.****.com
-
accounts.google.com/o/oauth2/…**********************.apps.googleusercontent.com&redirect_uri=https://*******.com/Callback&response_type =code&scope=googleapis.com/auth/drive
标签: java tomcat google-api google-drive-api google-api-java-client