我使用 google-api-java-client 访问 Google Cloud Storage API。它在我的本地机器和某些服务器上运行良好。但它在生产服务器上失败并出现 400 错误请求(错误:invalid_grant)。我在 Google Adwords API 上遇到了类似的问题,Google API Adwords Support 解决了这个问题。我认为他们只是将我使用的服务器的 IP 列入白名单。我是否可能需要在 Google Cloud Storage API 中添加权限?这会很奇怪,因为它可以在我的本地电脑上运行。
public class StorageObj {
private static final String KEY_FILE_NAME = "key.p12";
private static final String APPLICATION_NAME = "application_name";
private static final String BUCKET_NAME = "bucket_name";
private static final String STORAGE_OAUTH_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private final Storage storageObject;
public StorageObj() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_OAUTH_SCOPE))
.setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_NAME))
.build();
this.storageObject = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
;
}
public void insert(String folder, String file) throws IOException {
try (FileInputStream inputStream = new FileInputStream(new File(folder + file))) {
InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", inputStream);
mediaContent.setLength(inputStream.available());
Storage.Objects.Insert insertObject = storageObject.objects()
.insert(BUCKET_NAME, null /* obj-meta-data */, mediaContent)
.setName(file);
int _2MB = 2 * 1000 * 1000;
if (mediaContent.getLength() > 0 && mediaContent.getLength() <= _2MB) {
insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}
insertObject.execute();
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
new StorageObj().insert(args[0], args[1]);
}
}
}