我的项目是我在heroku上托管的java spark项目。项目的一部分要求我将特定文件从我的谷歌驱动器下载到应用程序中。当我的应用程序在本地运行时,我设法设置了所有内容,但是一旦部署应用程序,它就停止了工作。这是因为当应用程序在本地运行时,我使用了类型为other的Oauth2客户端ID,当我部署应用程序时,我创建了一个新的类型Web应用程序。
以下是身份验证和下载代码的片段:
public class AutoCalls {
/** Application name. */
private static final String APPLICATION_NAME = "calls-made";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("target/classes/auth"), ".credentials/calls-made");
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (GeneralSecurityException | IOException t) {
System.exit(1);
}
}
public static void startDownload() throws IOException, ParseException {
Drive serv = getDriveService();
// drive stuff deleted
}
public static Credential authorize() throws IOException {
InputStream in = new FileInputStream("target/classes/auth/client_secret_*****************************************.apps.googleusercontent.com.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
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");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
public static Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
}
目前,当我尝试启动下载时,我在Heroku日志中获得了一个URL:
2017-02-20T10:32:28.656820+00:00 app[web.1]: Please open the following address in your browser:
2017-02-20T10:32:28.656908+00:00 app[web.1]: https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=************-vvdi7u6bmp1vc90sdidtnuiftdi1t49c.apps.googleusercontent.com&redirect_uri=http://localhost:48085/Callback&response_type=code&scope=https://www.googleapis.com/auth/drive
当我尝试在浏览器中打开URL时出现错误:
Error: redirect_uri_mismatch
我找不到任何关于在java网络应用程序上访问谷歌驱动器内容的一步一步的好教程,所以任何帮助都会被提及。
答案 0 :(得分:0)
通常,如果OAuth在服务器A上工作但在服务器B上不工作,那是因为在API控制台上未正确配置重定向URL。您没有理由需要使用不同的客户端ID,因为可以使用多个URL配置单个客户端ID,例如本地主机和heroku服务器。另一种可能性是使用https。
您的代码中有一个单独的问题,您在lista.isEmpty()
上进行迭代。你应该在nextPageToken != null
上进行迭代。请参阅Google drive rest API, Download files from root folder only