问题描述
我有一个Java Web应用程序,可以在其中创建GCP VM实例并对其执行操作。
我使用Java Compute Engine API来执行创建,启动,停止等任务。
我想表演:
Compute compute = getComputeObj();
Suspend suspend = compute.instances().suspend(getProjectId(),getorder().getAvailabilityZone(),getorder().getMachineName());
Operation response = suspend .execute();
但是,我无法使用此API来“挂起”计算机,因为“挂起”处于beta版本(它不是Compute Engine v1 API的一部分,因此也不是Java包装器的一部分)。
-
创建一个java类“ ComputeBeta”,该类继承Compute类并实现Suspend类以执行该操作。这是有问题的,因为原始Compute类中的URL字段是final字段,因此我无法将URL从“ v1”更改为“ beta” URL。
-
执行与GCP beta API的“常规” http连接,以挂起计算机。这里的问题是我无法找到对API进行身份验证的正确语法,并且已经收到401响应。到目前为止,我已经尝试过:
String serviceAccountKey = getServiceAccountKey();
String baseUrl = "https://compute.googleapis.com";
String endpoint = "/compute/beta/projects/" + getorder().getProject()
+ "/zones/" + getorder().getAvailabilityZone() + "/instances/"
+ getorder().getMachineName() + "/suspend";
URL serverUrl = new URL(baseUrl + endpoint);
httpconnection = (HttpsURLConnection)serverUrl.openConnection();
httpconnection.setRequestMethod(HttpMethods.POST);
httpconnection.setDoOutput(true);
httpconnection.setDoInput(true);
httpconnection.setFixedLengthStreamingMode(length);
httpconnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
httpconnection.setRequestProperty("Authorization","Bearer " + serviceAccountKey);
httpconnection.connect();
int responseCode = httpconnection.getResponseCode();
String responseMessage = httpconnection.getResponseMessage();
在前进方面的任何帮助将不胜感激!
解决方法
您不必像这样使用服务帐户密钥。此密钥可让您创建凭据,然后使用它生成令牌。
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
// You can use explicitly your service account key file like this
// GoogleCredentials credentials = GoogleCredentials.fromStream(this.getClass().getResourceAsStream("my_key_file.json"));
String token = credentials.refreshAccessToken().getTokenValue();
...
httpConnection.setRequestProperty("Authorization","Bearer " + token);
您还可以使用Google Transport Factory来避免手动添加授权标头
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
// You can use explicitly your service account key file like this
// GoogleCredentials credentials = GoogleCredentials.fromStream(this.getClass().getResourceAsStream("my_key_file.json"));
HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(new HttpCredentialsAdapter(credentials));
// Here a GET request,but you can build a POST request also
HttpRequest request = factory.buildGetRequest(new GenericUrl("YOUR_URL"));
HttpResponse httpResponse = request.execute();
System.out.println(CharStreams.toString(new InputStreamReader(httpResponse.getContent(),Charsets.UTF_8)));
如果您有依赖关系问题(通常不是因为使用包含它的计算引擎库),您可以添加此依赖关系
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>0.21.1</version>
</dependency>