问题描述
由于公司的一些代理问题,我需要使用 Spring RestTemplate(绑定代理)而不是 aws sdk 或 spring cloud aws 消息从 AWS SQS 获取消息。
curl --location --request GET 'https://sqs.us-east-2.amazonaws.com/523535599964/MyAmazingQueue?Action=ReceiveMessage' \
--header 'X-Amz-Date: 20210623T133108Z' \
--header 'Authorization: AWS4-HMAC-SHA256 Credential=AKIAXTZJHJFOEKI4UF45/20210623/us-east-2/sqs/aws4_request,SignedHeaders=host;x-amz-date,Signature=2d926124ce07ca41c0f56af3bdddc81df19444df189b727ff02015f620cdfc6c'
这是由 Postman 生成的。
我需要用 java 生成这个签名并绑定到 HttpHeaders 对象。
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization",<generatedAuthString>);
headers.add("X-Amz-Date",<generatedAnother>);
.
.
httpentity<String> entity = new httpentity<>(null,headers);
response = restTemplate.exchange(url,HttpMethod.GET,entity,String.class);
我更喜欢使用 rest 模板,因为在添加如下代理时使用 aws sdk 不起作用。应用程序启动时出现超时错误。
public AmazonSQSAsync amazonSQSAsync() {
ClientConfiguration clientConfiguration= new ClientConfiguration();
clientConfiguration.setProxyHost(proxyurl);
clientConfiguration.setProxyPort(proxyport);
return AmazonSQSAsyncclientBuilder.standard().withRegion(region)
.withCredentials(new AWsstaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey,awsSecretKey)))
.build();
}
我尝试了这个 stackoverflow 问题中的每一项,但我得到了 AccessDeniedException 或 SignatureDoesNotMatch 异常。
How to generate Signature in AWS from Java
如果你能帮忙就好了。 谢谢。
解决方法
我终于解决了:)
AmazonSQSClientBuilder builder = AmazonSQSClientBuilder.standard();
AmazonSQS sqs = builder.withClientConfiguration(
PredefinedClientConfigurations.defaultConfig()
.withProxyHost("**")
.withProxyPort(****).withProxyPassword("***").withProxyUsername("****"))
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
我使用了 spring cloud aws 的 aws sdk 我使用了 ClientConfiguration 的 PredefinedClientConfigurations 。 谢谢大家!