【发布时间】:2014-01-30 11:41:06
【问题描述】:
我需要一些关于从 App Engine 代码中调用 Google Compute Engine API 的帮助。以下是我用来获取计算引擎实例列表的部分代码(简化版)
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。但是,使用 APIs Explorer 可以正常工作。
-
你有没有运气解决它?我又想到了一个想法——我们的 App Engine 项目是在前一段时间创建的,当时不可能在同一个项目中拥有 api——我们稍后在它可用时激活了它们。你有类似的设置吗?
-
是的,请参阅下面的答案。
标签: google-app-engine google-api google-compute-engine