避免读取消耗 AWS 响应的封闭流

Avoid reading closed stream consuming AWS Response

在调用我的 Elastic Search Service 对请求进行签名时,我仍然无法理解如何读取 AWS 响应的内容。似乎流在某处被消耗了。例如,我可以将响应内容打印为字符串的唯一方法是在 ResponseHandler 中。我正在使用亚马逊 AWS Java SDK 1.11.170.

AmazonHttpClient client = new AmazonHttpClient(new ClientConfiguration());

Response<Void> response = client
        .requestExecutionBuilder()
        .request(request)
        //.errorResponseHandler(errorHandler)
        .executionContext(context)
        //.execute(responseHandler)
        .execute()
;

System.out.println("response = " + convertStreamToString(response.getHttpResponse().getContent()));

这段代码分解为:

java.io.IOException: Attempted read from closed stream.

有没有办法在请求执行后并在响应处理程序之外保持流打开?

最终找到解决方案 github issue。 我必须使用正确的响应处理程序。这是:

public class StringResponseHandler implements HttpResponseHandler<AmazonWebServiceResponse<String>> {

    @Override
    public AmazonWebServiceResponse<String> handle(com.amazonaws.http.HttpResponse response) throws IOException {

        AmazonWebServiceResponse<String> awsResponse = new AmazonWebServiceResponse<>();

        //putting response string in the result, available outside the handler
        awsResponse.setResult((String) IOUtils.toString(response.getContent()));

        return awsResponse;
    }

    @Override
    public boolean needsConnectionLeftOpen() {
        return false;
    }

}

然后在调用者中:

AmazonHttpClient client = new AmazonHttpClient(new ClientConfiguration());

Response<AmazonWebServiceResponse<String>> response = client
        .requestExecutionBuilder()
        .request(request)
        .executionContext(context)
        .execute(new StringResponseHandler()) //note the new handler
        .execute()
;

//print the result (string expected)
System.out.println("aws response result = " + response.getAwsResponse().getResult();

如果你想使用第三方库,你可以使用Jest client plugged with Jest AWS signer