我正在编写一个App Engine Web应用程序,该应用程序从Google云端硬盘上的文件夹加载图片库。该代码在本地运行时效果很好(图像已正确检索并正确显示在网页上),但是在Google App Engine上部署时会中断。具体来说,启动以下方法时,返回的Drive服务为null,不会引发任何异常。凭据(SERVICE_ACCOUNT_EMAIL和PKCS12文件)应该正确,因为它们在本地运行代码时有效。我在这里想念什么?提前致谢。
public static Drive getDriveService() {
HttpTransport httpTransport = new NetHttpTransport();
GsonFactory jsonFactory = new GsonFactory();
GoogleCredential credential;
Drive service = null;
List<String> scopes = Arrays.asList(DriveScopes.DRIVE);
try {
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
service = new Drive.Builder(httpTransport, jsonFactory, null).setApplicationName("MyAppName")
.setHttpRequestInitializer(credential).build();
} catch (Exception e) {
e.printStackTrace();
}
return service;
}
实际上,可以使用两种方法通过Drive Api来对服务帐户进行身份验证。如果您正在使用Dev App Server在本地计算机上进行调试,则可以使用一个,但是一旦部署到GAE上将无法使用。您可以使用此代码段进行身份验证,该代码段摘自“驱动器API参考”
https://developers.google.com/drive/service-accounts#google_app_engine_project_service_accounts
只需将从控制台获得的API密钥放入代码中即可。这是我为Drive API的GAE身份验证找到的唯一可行的解决方案。
这是您要添加到项目中的代码:
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
...
/** The API Key of the project */
private static final String API_KEY = "the_api_key_of_the_project";
/**
* Build and returns a Drive service object authorized with the
* application's service accounts.
*
* @return Drive service object that is ready to make requests.
*/
public static Drive getDriveService() throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
AppIdentityCredential credential =
new AppIdentityCredential.Builder(DriveScopes.DRIVE).build();
GoogleClientRequestInitializer keyInitializer =
new CommonGoogleClientRequestInitializer(API_KEY);
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.setGoogleClientRequestInitializer(keyInitializer)
.build();
return service;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句