在我打电话给我的弹性搜索服务签署请求时,我仍然无法理解如何阅读AWS响应的内容。似乎流被消耗在某个地方。例如,我可以将响应内容打印为字符串的唯一方法是在ResponseHandler中。我正在使用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()));
此代码分解并说:
java.io.IOException: Attempted read from closed stream.
有没有办法在请求执行后和响应处理程序之外保持流打开?
答案 0 :(得分:1)
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