【发布时间】:2023-03-28 13:18:01
【问题描述】:
我正在努力使用 Java 通过 REST API 调用 GCP 云功能。
我执行的步骤是:
- 创建角色为“Cloud Functions Invoker”的服务帐号
- 为新创建的服务帐号下载 JSON 密钥文件
- 在我的代码中,使用以下方法获取访问令牌:
private String getAuthToken() {
File credentialsPath = new File(PATH_TO_JSON_KEY_FILE);
GoogleCredentials credentials;
try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
return credentials
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"))
.refreshAccessToken()
.getTokenValue();
} catch (IOException e) {
throw new RuntimeException("Action could not be performed");
}
}
- 使用创建的令牌执行 REST 调用:
public <Payload, Response> ResponseEntity<Response> callCloudFunction(
String endpoint,
Payload payload,
Class<Response> klazz
) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
String url = gCloudUrl + endpoint;
String token = getAuthToken();
String payloadString = null;
if (payload != null) {
try {
ObjectMapper objectMapper = new ObjectMapper();
payloadString = objectMapper.writeValueAsString(payload);
} catch (JsonProcessingException e) {
System.out.println(e.getMessage());
throw new RuntimeException("Could not perform action");
}
}
headers.add("Authorization", String.format("Bearer %s", token));
HttpEntity<String> entity = new HttpEntity<>(payloadString, headers);
return restTemplate.exchange(url, HttpMethod.POST, entity, klazz);
}
实现看起来不错,但作为响应,我得到 401 Unauthorized。
很遗憾,GCP 文档并没有真正的帮助。我想我已经搜索了所有可能的地方。
【问题讨论】:
-
这是我的解决方案:stackoverflow.com/a/64720883/14592586 看看它是否有助于解决问题。
标签: java rest google-cloud-platform google-cloud-functions