GoogleCloudPlatform/storage/cloud-client sample可以在GCE VM上运行 但是当我在我的本地机器(Win7_64x)上运行时,我得到了StorageException(401 Unauthorized) 我按this doc设置了身份验证。
程序可以从我的本地计算机访问谷歌存储吗? 我还能做些什么才能做到这一点?或者没有办法在GCP之外访问谷歌存储?
Exception in thread "main" com.google.cloud.storage.StorageException: 401 Unauthorized
at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:191)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:221)
at com.google.cloud.storage.StorageImpl$2.call(StorageImpl.java:112)
at com.google.cloud.storage.StorageImpl$2.call(StorageImpl.java:109)
at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:89)
at com.google.cloud.RetryHelper.run(RetryHelper.java:74)
at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:51)
at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:108)
at com.example.storage.QuickstartSample.main(QuickstartSample.java:35)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:219)
... 7 more
UPDATE(20180309):
使用 hard-coded Service Account Credentials 运行以下代码,我可以访问Google存储并从中下载文件。
String SERVICE_ACCOUNT_JSON_PATH = "C:\\gcpconfig\\My First Project-6f9cff47c4f0.json";
Storage storage =
StorageOptions.newBuilder()
.setCredentials(
ServiceAccountCredentials.fromStream(
new FileInputStream(SERVICE_ACCOUNT_JSON_PATH)))
.build()
.getService();
BlobId blobId = BlobId.of("nmjcloud_jar_test","addons/simple-bean-1.0.jar");
Blob blob = storage.get(blobId);
Path path = Paths.get("D:\\lib\\simple-bean-1.0.jar");
blob.downloadTo(path);
System.out.printf("Download successfully%n");
很遗憾,将 GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为我的密钥json文件的完整路径仍然无法正常工作。似乎google存储api库没有从GOOGLE_APPLICATION_CREDENTIALS
读取关键的json文件。