1

I still can't understand how to read the content of an AWS response while I'm doing calls to my Elastic Search Service signing the requests. It seems like the stream is consumed somewhere. The only way I can, for example, print the response content as a string, is inside a ResponseHandler. I'm using Amazon 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()));

This code breaks down and says:

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

Is there a way to keep the stream open after the request execution and outside the response handler?

Stefano Lazzaro
  • 387
  • 1
  • 4
  • 22
  • What AWS service are you using? IMO you are using a very low-level library and should rather be using the service-specific SDK that AWS provides. – ketan vijayvargiya Aug 04 '17 at 10:10
  • Invoking Elastic Search Service, that unfortunately has no Java client, so basically I'm using a simple AmazonHttpClient. Anyway, I added these details on my question, thank you! – Stefano Lazzaro Aug 04 '17 at 10:29

1 Answers1

3

Eventually found the solution perusing this github issue. I had to use the right response handler. Here it is:

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;
    }

}

And then in the caller:

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();

If you want to go with third party libs, you can use Jest client plugged with Jest AWS signer

Stefano Lazzaro
  • 387
  • 1
  • 4
  • 22