【发布时间】:2016-01-22 03:11:50
【问题描述】:
我想将 Google Drive 集成到我们的网络应用程序中。因此,每个用户都可以将他的 Google Drive 存储连接到我们的应用程序以存储文件。为此目的正确的授权方式是什么?
OAuth 是否正确?我知道在开发者控制台中创建凭据,但是如何将 Google 凭据与我们的帐户关联、存储并在稍后上传文件时使用?
我想在OAuth登录后实现向用户驱动器写入/读取文件。
这是我的代码,它使用服务凭据。我知道这是错误的方式。
public class GDManager {
private static String accountId = "xxx@developer.gserviceaccount.com";
private static String p12File = "file.p12";
private static GoogleCredential buildCredential(HttpTransport httpTransport, JsonFactory jsonFactory) throws GeneralSecurityException, IOException {
// Build service account credential.
return new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(accountId)
.setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE))
.setServiceAccountPrivateKeyFromP12File(new java.io.File(GDManager.class.getClassLoader().getResource(p12File).getFile()))
.build();
}
private static Drive init() {
try {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = buildCredential(httpTransport, jsonFactory);
return new Drive.Builder(
httpTransport, jsonFactory, credential)
.setApplicationName("Google drive test")
.build();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
Drive service = init();
String parentId = null;
String mimeType = "text/plain";
File body = new File();
body.setTitle("test");
body.setDescription("description");
body.setMimeType(mimeType);
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
java.io.File fileContent = new java.io.File("/home/michal/Downloads/google_drive");
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
System.out.println(file);
} catch (IOException e) {
System.out.println("An error occured: " + e);
}
}
}
【问题讨论】:
-
您到底想达到什么目标?您的要求有点难以理解。当用户使用 Google OAuth 登录您的应用时,您希望对用户的 Google Drive 进行读/写访问,对吧?
-
是的,完全正确。 OAuth 登录后的读/写访问权限。
-
好的。你能告诉我们你到目前为止做了什么吗?
-
我添加了带有主要方法的样本用于测试目的。
-
不显示示例。显示您的代码和特定问题。有很多官方文档和完整示例。 oauth 是正确(也是唯一)的方式。不需要 p12 或服务帐户。阅读每种方法的差异。你想要 3legged oauth2
标签: java google-drive-api