How to generate Signature in AWS from Java

前端 未结 6 611
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 10:19

When I invoke API endpoints from REST client, I got error by concerning with Signature.

Request:

Host: https://xxx.execute-ap

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 10:38

    You can use classes from aws-java-sdk-core: https://github.com/aws/aws-sdk-java/tree/master/aws-java-sdk-core

    More specifically, Request, Aws4Signer and a few other ones:

    //Instantiate the request
    Request request = new DefaultRequest("es"); //Request to ElasticSearch
    request.setHttpMethod(HttpMethodName.GET);
    request.setEndpoint(URI.create("http://..."));
    
    //Sign it...
    AWS4Signer signer = new AWS4Signer();
    signer.setRegionName("...");
    signer.setServiceName(request.getServiceName());
    signer.sign(request, new AwsCredentialsFromSystem());
    
    //Execute it and get the response...
    Response rsp = new AmazonHttpClient(new ClientConfiguration())
        .requestExecutionBuilder()
        .executionContext(new ExecutionContext(true))
        .request(request)
        .errorResponseHandler(new SimpleAwsErrorHandler())
        .execute(new SimpleResponseHandler());
    

    If you want a cleaner design, you can use the Decorator pattern to compose some elegant classes and hide the above mess. An example for that here: http://www.amihaiemil.com/2017/02/18/decorators-with-tunnels.html

提交回复
热议问题