我正在编写一个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;
}
答案 0 :(得分:1)
实际上有两种方法可以使用Drive Api对服务帐户进行身份验证。如果您使用Dev App Server在本地计算机上进行调试,那么您正在使用的那个是好的,但是一旦部署到GAE就无法工作。 您可以使用此代码段进行身份验证,该代码段取自
上的Drive 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;
}
答案 1 :(得分:0)
通常,要调试Oauth,请打开日志记录并检查线路上的内容。显然,无论是在本地还是在GAE,您都在寻找差异。
由于您的代码对于两种环境都是相同的,因此这不是问题的可能来源。有些事要检查......