Reputation: 5087
I am trying to log the request-response pairs for every request. The problem is that when the response code is 401
, ClientHttpResponse.getBody()
throws a ResourceAccessException and i cannot read the response body.
This is the RestTemplate configuration
RestTemplate restTemplate = new RestTemplate();
// Added this requestFactory to make response object readable more than once.
ClientHttpRequestFactory requestFactory =
new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
restTemplate.setRequestFactory(requestFactory);
restTemplate.getInterceptors().add(new RequestLoggingInterceptor(vCloudRequest.getAction(),httpHeaders));
restTemplate.setErrorHandler(new RequestErrorHandler());
return restTemplate;
The last line of the interceptor below throws the following exception.
How can i resolve this problem?
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://example.com/api/sessions": Server returned HTTP response code: 401 for URL: https://example.com/api/sessions; nested exception is java.io.IOException: Server returned HTTP response code: 401 for URL: https://example.com.11/api/sessions
This is the related part of the interceptor.
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
String requestString = new String(body);
// Calling this method because when we make a POST or PUT request and get an error
// response.getBody() throws IOException. But if we call response.getStatusCode() it works fine.
// I don't know the reason.
// I asked a question on stackoverflow
// https://stackoverflow.com/questions/47429978/resttemplate-response-getbody-throws-exception-on-4-and-5-errors-for-put-and
response.getStatusCode();
String responseString = new String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"));
...
}
This is the custom error handler
public class RequestErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
if (!response.getStatusCode().is2xxSuccessful()) {
return true;
}
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
JAXBElement<ErrorType> root = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(ErrorType.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
root = jaxbUnmarshaller.unmarshal(new StreamSource(
response.getBody()), ErrorType.class);
} catch (JAXBException e) {
throw new IOException("XML converting error. Cannot convert response to ErrorType");
}
ErrorType error = root.getValue();
throw new VcloudException(error);
}
}
Upvotes: 8
Views: 17566
Reputation: 2146
Use HttpComponentsClientHttpRequestFactory instead of SimpleClientHttpRequestFactory.
Also add dependency to 'org.apache.httpcomponents:httpclient.
HttpComponentsClientHttpRequestFactory ccan read body when status is 401.
Upvotes: 4
Reputation: 3008
I do not think, ResourceAccessException
is being thrown by response.getBody()
, instead seems to be that ByteStreams.toByteArray(...)
is sending probably a null
stream in response.
Can you please try debugging if response.getBody()
is null
or it's ByteStreams.toByteArray()
. Because RescourceAccessException is thrown when an I/O error occurs.
Upvotes: 0
Reputation: 6944
Spring RestTemplate as default generates an error when httpstatus is not 200.
In my past project what I did is to add a custom org.springframework.web.client.ResponseErrorHandler
to the rest template.
You may wrote a class like this:
public class SimpleRestErrorHandler implements ResponseErrorHandler
{
private static final Logger logger = LoggerFactory.getLogger(SimpleRestErrorHandler.class.getName());
@Override
public boolean hasError(ClientHttpResponse response) throws IOException
{
int statusCode = response.getStatusCode().value();
if( logger.isDebugEnabled() )
{
logger.debug("STATUS CODE ["+statusCode+"] ");
}
//Generate Error only when HTTP Status code is 500
if( statusCode == 500 )
{
return true;
}
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException
{
//Here you can manage the error (in this sample only the http status code = 500
}
}
Then I added this to my rest template:
XML configuration sample
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="bufferingClientHttpRequestFactory" /> <property name="errorHandler" ref="simpleRestErrorHandler" /> <property name="messageConverters"> <list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="#{T(java.nio.charset.Charset).forName('UTF-8')}" />
</bean>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean
class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean
class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter" />
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </list> </property> <property name="interceptors"> <!-- Custom interceptors --> </property> </bean> <bean id="bufferingClientHttpRequestFactory" name="bufferingClientHttpRequestFactory" class="org.springframework.http.client.BufferingClientHttpRequestFactory"> <constructor-arg ref="simpleReqFact" /> </bean> <bean id="simpleRestErrorHandler" class="handlers.SimpleRestErrorHandler" />
Java config
@Config
public class restTemplConfig {
@Bean
public RestTemplate restTempl() {
RestTemplate result = new RestTemplate();
//Add converters
//Add custom error handler
result.setErrorHandler(new SimpleRestErrorHandler());
}
}
I hope it's useful
Upvotes: -1