我需要在App Engine代碼中使用Google Compute Engine API調用的一些幫助。以下是代碼的一部分,我用它來獲取計算引擎實例的列表(簡體版)計算引擎API調用失敗,使用http 404
try {
final AppIdentityService appIdService = AppIdentityServiceFactory
.getAppIdentityService();
AppIdentityService.GetAccessTokenResult result = appIdService
.getAccessTokenUncached(Collections
.singletonList(ComputeScopes.COMPUTE));
String accessToken = result.getAccessToken();
String url = "https://www.googleapis.com/compute/v1/projects/MYPROJECTID/zones/us-central1-b/instances";
String payload = "";
// Create HTTPRequest and set headers
HTTPRequest httpRequest = new HTTPRequest(new URL(url.toString()),
HTTPMethod.GET, FetchOptions.Builder.doNotFollowRedirects());
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth "
+ accessToken));
httpRequest.addHeader(new HTTPHeader("Host", "www.googleapis.com"));
httpRequest.addHeader(new HTTPHeader("Content-Length", Integer
.toString(payload.length())));
httpRequest.addHeader(new HTTPHeader("Content-Type",
"application/json"));
httpRequest.addHeader(new HTTPHeader("User-Agent",
"google-api-java-client/1.0"));
httpRequest.setPayload(payload.getBytes());
URLFetchService fetcher = URLFetchServiceFactory
.getURLFetchService();
HTTPResponse httpResponse = fetcher.fetch(httpRequest);
int responseCode = httpResponse.getResponseCode();
if ((responseCode == 200) || (responseCode == 204)) {
String contentStr = new String(httpResponse.getContent());
return extractIpsAndInstanceNames(contentStr, prefix);
} else {
logger.warning("Failed. Response code " + responseCode
+ " Reason: " + new String(httpResponse.getContent()));
}
正如你可以看到我使用AppIdentity獲得訪問令牌。然後在API調用的請求頭中使用它。每次調用失敗與以下錯誤時間
基本上
Failed. Response code 404 Reason: {
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "The resource 'projects/MYPROJECTID' was not found"
}
],
"code": 404,
"message": "The resource 'projects/MYPROJECTID' was not found"
}
}
有趣的是,如果我用下面的webapp https://developers.google.com/compute/docs/reference/latest/instances/list#try-it也作出了同樣的API調用它成功。
因此,我研究了當這個Web應用程序發出請求並複製持票人標記字符串並在「授權」標題中使用它時會發送什麼數據。奇怪的是,請求現在已經成功完成了,而沒有改變其他任何東西基本上,該應用程序使用用戶同意Oauth2類型的令牌 - 對我來說,它看起來像通過AppIdentity獲得的令牌有一些問題。 有人能指引我正確的方向嗎?謝謝!
我已經看到與Go運行時完全相同的問題。我正在請求使用內置的應用程序引擎服務帳戶列出來自應用程序引擎的計算圖像,並且我得到了404。然而,使用API瀏覽器可以正常工作。 –
你有沒有解決它的運氣?我還有一個想法 - 我們的App Engine項目是在一段時間之前創建的,因爲在同一個項目中不可能有apis - 我們在稍後可用時激活它們。你有類似的設置嗎? –
是的,請參閱下面的答案。 –