【发布时间】:2017-07-04 16:08:00
【问题描述】:
我正在创建一个应用程序,我必须在其中将文件存储在登录用户的 Google 驱动器中,这样无论哪个用户登录,他都可以将数据存储在他的驱动器上。现在我遇到了如何从代码生成 Google Drive 凭据(clientId、clientSecret 和 refreshToken)的问题,正如我看到的所有示例一样,要求转到 Google 控制台并执行此操作。有没有我们可以使用 java 代码实现它。其实我需要使用谷歌驱动广告数据库存储。 使用了以下代码:但需要客户端 ID。
public class Main
{
public static void main(String[] args)
{
String clientId = "...";
String clientSecret = "...";
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
jsonFactory,
clientId,
clientSecret,
Arrays.asList(DriveScopes.DRIVE)
)
.setAccessType("online")
.setApprovalPrompt("auto").build();
String redirectUri = "urn:ietf:wg:oauth:2.0:oob";
String url =
flow
.newAuthorizationUrl()
.setRedirectUri(redirectUri)
.build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response =
flow
.newTokenRequest(code)
.setRedirectUri(redirectUri)
.execute();
GoogleCredential credential =
new GoogleCredential()
.setFromTokenResponse(response);
Drive service =
new Drive.Builder(httpTransport, jsonFactory, credential)
.build();
...
}
}
【问题讨论】:
标签: google-drive-api