我正在使用 DriveCommandLine 应用程序来学习 Drive API。我只是想知道是否可以使用 Google Drive 对我的桌面应用程序进行身份验证,而无需用户从浏览器复制/粘贴身份验证代码?而是只是将令牌从浏览器传回应用程序?我可以使用 Dropbox API 和 Google Documents List API 来做到这一点,但无法弄清楚如何使用 Google Drive API 来实现这一点。
谢谢。
Google Drive API - DriveCommandLine 示例应用(稍作修改):
public class DriveCommandLine {
private static String CLIENT_ID = APPCONSTANTS.Google.CONSUMER_KEY;
private static String CLIENT_SECRET = APPCONSTANTS.Google.CONSUMER_SECRET;
private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
public static void main(String[] args) throws IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("offline")
.setApprovalPrompt("force").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Enter authorization code:");
Desktop.getDesktop().browse(new URI(url));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
}
谷歌文档列表 API:
public void authenticate(){
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(APPCONSTANTS.Google.CONSUMER_KEY);
OAuthSigner signer;
if (APPCONSTANTS.Google.USE_RSA_SIGNING) {
signer = new OAuthRsaSha1Signer(APPCONSTANTS.Google.CONSUMER_SECRET);
} else {
oauthParameters.setOAuthConsumerSecret(APPCONSTANTS.Google.CONSUMER_SECRET);
signer = new OAuthHmacSha1Signer();
}
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
oauthParameters.setScope(APPCONSTANTS.Google.SCOPES);
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
Desktop desktop = Desktop.getDesktop();
URI url = new URI(requestUrl);
desktop.browse(url);
String token = oauthHelper.getAccessToken(oauthParameters);
}