AWS EC2 webservice调用

时间:2018-03-29 11:09:10

标签: amazon-web-services amazon-ec2

尝试在EC2上托管网络服务

使用https://github.com/javaquery/Examples/blob/master/src/com/javaquery/aws/AWSV4Auth.java

中提供的代码

我已经通过了标题:X-Amz-Date,授权进行服务调用但仍然得到响应 {“message”:“缺少身份验证令牌”}

以下是我的代码段

AWSV4Auth aWSV4Auth = new AWSV4Auth.Builder(accessKey, secretKey)
                                .regionName(awsRegion).serviceName(awsServiceName) 
                                .httpMethodName("POST")
                                .canonicalURI("endpoint") // end point
                                .queryParametes(null) // query parameters if any
                                .awsHeaders(awsHeaders) // aws header parameters
                                //.payload(inputPayload) // payload
                                .build();

Map<String, String> header = aWSV4Auth.getHeaders();

WebResource webResource = client.resource(endpointURL);     
webResource.header("Content-Type", contentType);
webResource.header("X-Amz-Date", header.get("x-amz-date"));//X-Amz-Date
webResource.header("Authorization", header.get("Authorization"));//Authorization

ClientResponse response = webResource.type("application/json").post(ClientResponse.class, inputPayload);                 
String payLoad = response.getEntity(String.class);
你可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

使用apache http client

使用下面的代码
StringEntity se = new StringEntity(inputPayLoad);
            org.apache.http.client.HttpClient client = HttpClients.custom().build();
            HttpUriRequest request = RequestBuilder.post()
                                      .setEntity(se)
                                      .setUri(serviceURL)
                                      .setHeader("X-Amz-Date", header.get("x-amz-date"))
                                      .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                                      .setHeader("Authorization", header.get("Authorization"))
                                      .setHeader("Host", awsHost)
                                      .build();
            org.apache.http.HttpResponse httpResponse = null;
            httpResponse = client.execute(request);         
            ResponseHandler<String> handler = new BasicResponseHandler();           
            response = handler.handleResponse(httpResponse);