我不想将生成的SDK用于我的API网关端点。我想使用普通的AWS SDK。当我用谷歌搜索如何做到这一点时,在前几次命中(令人惊讶的)中没有出现任何明显的结果。所以我拼凑了这个:
private static void invokeApiGatewayWithCognito(String identityPoolId, String endpoint) throws URISyntaxException {
AmazonCognitoIdentity cognitoClient = AmazonCognitoIdentityClient.builder()
.withCredentials(new AWSCredentialsProvider() {
@Override
public AWSCredentials getCredentials() {
return new AnonymousAWSCredentials();
}
@Override
public void refresh() {
}
}).withRegion(EU_CENTRAL_1.getName()).build();
String identityId = cognitoClient.getId(new GetIdRequest()
.withIdentityPoolId(identityPoolId))
.getIdentityId();
Credentials cognitoCreds = cognitoClient
.getCredentialsForIdentity(
new GetCredentialsForIdentityRequest()
.withIdentityId(identityId))
.getCredentials();
AWS4Signer signer = new AWS4Signer();
signer.setServiceName("execute-api");
signer.setRegionName(EU_CENTRAL_1.getName());
AmazonHttpClient amazonHttpClient =
new AmazonHttpClient(new ClientConfiguration());
Request r = new DefaultRequest("execute-api");
r.setEndpoint(new URI(endpoint));
r.setHttpMethod(HttpMethodName.GET);
BasicSessionCredentials basicCreds = new BasicSessionCredentials(
cognitoCreds.getAccessKeyId(),
cognitoCreds.getSecretKey(),
cognitoCreds.getSessionToken());
signer.sign(r, basicCreds);
amazonHttpClient
.requestExecutionBuilder()
.request(r)
.execute(logResponse());
}
private static HttpResponseHandler<Void> logResponse() {
return new HttpResponseHandler<Void>() {
@Override
public Void handle(HttpResponse httpResponse) throws Exception {
System.out.println("response code = " + httpResponse.getStatusCode());
System.out.println("response headers = " + httpResponse.getHeaders());
System.out.println("response content = " + new String(bytes(httpResponse.getContent())));
return null;
}
@Override
public boolean needsConnectionLeftOpen() {
return false;
}
};
}
它有效,但男孩是那个丑陋的代码。我错过了什么?如何更干净地完成这项工作?