【发布时间】:2018-07-17 18:51:13
【问题描述】:
我正在尝试从我的 Java 应用程序附加到现有的 Google 表格,但我不断收到一条错误消息,提示“不允许为空或缺少范围。”
对我来说奇怪的是,当我将我的应用程序部署到 OpenShift 时,我只收到此错误。我创建了一个测试用例来在本地运行相同的代码,并且 Google 表格实际上已经更新而没有问题。
所以在我把这台笔记本电脑从大楼屋顶扔掉之前,谁能帮我看看我做错了什么?
public class SpreadsheetClient {
private static final Logger LOG = LoggerFactory.getLogger(SpreadsheetClient.class);
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String APPLICATION_NAME = "My App";
private static final String START_RANGE = "A2";
private static final String VALUE_INPUT_OPTION = "RAW";
private static final String INSERT_DATA_OPTION = "INSERT_ROWS";
private Sheets sheets;
public SpreadsheetClient(String certPath) throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
sheets = new Sheets.Builder(httpTransport, JSON_FACTORY, GoogleUtil.getGoogleCredential(certPath, SCOPES))
.setApplicationName(APPLICATION_NAME).build();
}
public void appendRows(String sheetId, List<List<Object>> values, Handler<AsyncResult<Void>> handler) {
try {
AppendValuesResponse response = sheets.spreadsheets().values().append(sheetId, START_RANGE, new ValueRange().setValues(values))
.setValueInputOption(VALUE_INPUT_OPTION)
.setInsertDataOption(INSERT_DATA_OPTION)
.execute();
if (response.getUpdates().getUpdatedRows() == values.size()) {
handler.handle(Future.succeededFuture());
}
else {
LOG.error("Expected to update {} rows, updated {} instead", values.size(), response.getUpdates().getUpdatedRows());
JsonArray updateValues = new JsonArray(response.getUpdates().getUpdatedData().getValues());
LOG.debug("The update values are {}", updateValues);
handler.handle(ServiceException.fail(NOT_ENOUGH_ROWS_UPDATED.code(), updateValues.encode()));
}
}
catch (IOException ex) {
LOG.error("Failed to append to spreadsheet", ex);
handler.handle(Future.failedFuture(ex));
}
}
}
这是我的凭证文件(显然已经去掉了真实的凭证):
{
"type": "service_account",
"project_id": "account",
"private_key_id": "an_id",
"private_key": "-----BEGIN PRIVATE KEY-----\nstuff\n-----END PRIVATE KEY-----\n",
"client_email": "service@account.iam.gserviceaccount.com",
"client_id": "another_id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service%40account.iam.gserviceaccount.com"
}
【问题讨论】:
-
在本地进行测试时,您是否确定确实使用了凭证文件?有时 google sdk 会自动获取您的本地凭据。
标签: java google-api google-sheets-api google-api-java-client