Running Spring 4.2.6.RELEASE, we are experiencing unexpected behavior with fairly typical RestTemplate usage; a 401 error is not being translated to a HttpClientErrorException.
Specifically, when we receive an expected 401 from the server, we receive a ResourceAccessException wrapping an IOException with the message Server returned HTTP response code: 401 for URL: ..., which is raised deep within the bowels of sun.net.www.protocol.http.HttpURLConnection.
Our template is configured more or less like so:
public RestTemplate restTemplate() {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
// connections per route is not a meaningful limit for us, so set very high
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10000);
poolingHttpClientConnectionManager.setMaxTotal(100);
CloseableHttpClient client = HttpClientBuilder.create().setConnectionManager(poolingHttpClientConnectionManager).build();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
Our usage of the client looks like:
protected <T, U> ResponseEntity<T> request(UserClientAccount account, U body, String url, HttpMethod httpMethod,
ParameterizedTypeReference<T> responseType, boolean retry) {
try {
HttpEntity<U> request = createHttpEntity(body, account.getToken(this));
return getRestTemplate().exchange(url, httpMethod, request, responseType, new HashMap<String, String>());
}
catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
if (retry) {
log.warn("Unauthorized response for {}. Refreshing token to retry...", url);
refreshToken(account);
// tries again
return request(account, null, url, httpMethod, responseType, false);
}
else {
log.error("Unauthorized error calling {}. All attempts to retry exhausted ", url);
throw e;
}
}
throw new ProgramException("Error while performing " + httpMethod + " request to " + url + ". " +
"Response body: " + e.getResponseBodyAsString(), e);
}
}
Our catch of HttpClientErrorException is never hit; instead, we receive a ResourceAccessException with a cause of the above mentioned IOException.
What are we doing wrong?
Related
I have a REST API to call and I have written the client using rest template. When executing, I am getting 400 status code. The same REST API is working fine when using POSTMAN. Below are the code snippets for API and caller. Do let me know if anyone catches anything.
REST API for POST method-
#ApiOperation(value = "Download repository as zip")
#ApiResponses({#ApiResponse(code = 200, message = ""), #ApiResponse(code = 400, message = "")})
#PostMapping(value = "/download", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
public ResponseEntity<StreamingResponseBody> downloadRepository(
#RequestBody #Validated final RepositoriesRequest repositoriesRequest) {
final Situation situation = this.situationsService.getSituationId(repositoriesRequest);
if (isNull(situation)) {
return ResponseEntity.notFound().build();
} else {
final ExtractionRequest extractionRequest = new ExtractionRequest(repositoriesRequest.getType(), situation,
repositoriesRequest.getDatabase());
if (!this.validateRequest(extractionRequest)) {
return ResponseEntity.badRequest().build();
}
final ExtractionResponse response = this.extractService.extractRepository(extractionRequest);
if (null == response) {
return ResponseEntity.notFound().build();
}
final InputStream inputStream = this.extractService.getFileFromS3(response.getRepositoryPath());
if (null == inputStream) {
return ResponseEntity.noContent().build();
}
final StreamingResponseBody bodyWriter = this.bodyWriter(inputStream);
return ResponseEntity.ok()
.header("Content-Type", "application/zip")
.header(CONTENT_DISPOSITION, "attachment; filename=\"repository-" + situation.getId() + ".zip\"")
.body(bodyWriter);
}
}
REST CLIENT using Rest Template with auth token and request body as input -
HttpEntity<MultiValueMap<String, Object>> buildLoadRepoRequest(
final SimulationContext context,
final List<String> tablesName,
final String simulationId,
final Integer offset) {
final Token token = this.authenticateOkoye(simulationId, offset);
LOGGER.info("Token Run: {}", token.getAccessToken());
final String database = this.getDatabaseForEnvironment();
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(APPLICATION_JSON_UTF8);
httpHeaders.set(AUTHORIZATION, "Bearer " + token.getAccessToken());
final MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("database", database);
body.add("monthlyClosingMonth", context.getMonthlyClosingDate());
body.add("repositorySnapshot", context.getRepository());
body.add("situationId", context.getSituationId());
body.add("tableNames", tablesName);
body.add("type", context.getRunType());
return new HttpEntity<>(body, httpHeaders);
}
Exception Handler -
#Override
#ExceptionHandler(HttpClientErrorException.class)
public void loadRepository(
final SimulationContext context,
final List<String> tablesName,
final String simulationId,
final Integer offset,
final Path repositoryPath) throws IOException {
LOGGER.info("[{}] [{}] repository tablesName: {}", simulationId, offset, tablesName);
this.restTemplate.setRequestFactory(this.getClientHttpRequestFactory());
final ClientHttpResponse response = this.restTemplate.postForObject(
this.repositoriesUrl,
this.buildLoadRepoRequest(context, tablesName, simulationId, offset),
ClientHttpResponse.class);
if (response != null && HttpStatus.OK == response.getStatusCode()) {
LOGGER.info(
"response status on simulation : {} - Context: {} - status: {}",
simulationId,
offset,
response.getStatusCode());
//this.helper.copy(response.getBody(), repositoryPath);
} else if (response != null && HttpStatus.NO_CONTENT != response.getStatusCode()) {
throw new JarvisException(
"Can't retrieve RWA repository on simulation " + simulationId + " Context:" + offset);
}
}
We have been looking into this issue since yesterday and still don't have any clue. So far we have tried postForEntity, exchange, changing the headers to proper setter methods and tried passing the parameters as an object also. None of them worked.
I have a strong feeling about something being wrong at header level while calling the API.
Did you try to use httpHeaders.setContentType(MediaType.APPLICATION_JSON)
Or add consumes to #PostMapping annotation with APPLICATION_JSON_UTF8 value
I created a generic method to call an external API (post call). Everything is working fine if external rest API returns 2** but, in case of any error an exception is raised.
Isn't is possible to treat this 4** response like a normal answer instead of generate an exception? The problem is that I need to get the error message (response body) and send back to the caller.
This is my code:
public ResponseEntity<String> post(String api, Map<String, Object> data) {
ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK);
try {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
log.debug("post(): " + host + "/" + api );
// Set the headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Convert the Map to Gson
Gson gson = new Gson();
String json = gson.toJson(data);
// Call the API
HttpEntity<?> request = new HttpEntity<>(json, headers);
response = new RestTemplate().postForEntity(host + "/" + api, request, String.class);
stopwatch.split();
log.info("All request completed [" + response.getStatusCode() + "] in " + stopwatch.getSplitTime());
return response;
} catch (Exception ex) {
log.error(ex);
throw new RuntimeException();
}
}
The external API, in case of error, returns this:
ResponseEntity<Integer> response = new ResponseEntity<Integer>();
[.. business code ..]
res.setResponse(new ResponseEntity<String>(CommonValue.userNotFound, HttpStatus.UNAUTHORIZED));
Use RestTemplate#exchange(..) methods that return a ResponseEntity. This will not throw an exception but will parse the answer into the ResponseEntity where you can retrieve the status code etc.
I have an external partner that uses OAuth 1.0 to protect some resources. I need to access this resources and I would like to do this using Spring Boot and Spring Security OAuth. As I don't want to use XML configuration, I already searched for a way to set up everything via Java configuration. I found this thread that provided an example of how to do this. But serveral things regarding the OAuth 1.0 flow are not clear for me.
My partner provides four endpoints for OAuth: an endpoint that provides a consumer token, a request_token endpoint, an authorization endpoint and an access_token endpoint. With my current setup (shown below) I can get a request token and the authorization endpoint gets called. However, the authorization endpoint does not ask for confirmation, but expects as URL parameters an email and a password and, after checking the credentials, returns the following:
oauth_verifier=a02ebdc5433242e2b6e582e17b84e313
And this is where the OAuth flow gets stuck.
After reading some articles about OAuth 1.0 the usual flow is this:
get consumer token / key
get oauth token using the consumer token via request_token endpoint
redirect to authorization URL and ask the user for confirmation
redirect to consumer with verifier token
user verifier token and oauth token to get access token via access_token endpoint
First of all: steps 3 and 4 are not clear to me. I've found the Spring Security OAuth examples, but it wasn't clear to me how, after confirming the access, the user / verifier token get send back to the consumer. Could someone please explain how this is done?
Second: Given that my partners endpoint does not ask for confirmation but returns an oauth verifier right away, how can I use Spring Security OAuth with this setup? I was thinking about implementing my own authorization endpoint that calls the authorziation endpoint of my partner and then somehow makes the verifier known to my consumer, but I'm not sure how to do the latter part.
Here is the code so far (with help for the thread mentioned above; the ConsumerTokenDto has been left out as it is trivial):
Application
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Endpoint
#RestController
public class Endpoint {
#Autowired
private OAuthRestTemplate oAuthRestTemplate;
private String url = "https://....";
#RequestMapping("/public/v1/meters")
public String getMeters() {
try {
return oAuthRestTemplate.getForObject(URI.create(url), String.class);
} catch (Exception e) {
LOG.error("Exception", e);
return "";
}
}
}
OAuth configuration
#Configuration
#EnableWebSecurity
public class OAuthConfig extends WebSecurityConfigurerAdapter {
#Autowired
private RestTemplateBuilder restTemplateBuilder;
private ConsumerTokenDto consumerTokenDto;
private static final String ID = "meters";
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll();
http.addFilterAfter(this.oauthConsumerContextFilter(), SwitchUserFilter.class);
http.addFilterAfter(this.oauthConsumerProcessingFilter(), OAuthConsumerContextFilterImpl.class);
}
private OAuthConsumerContextFilter oauthConsumerContextFilter() {
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter();
filter.setConsumerSupport(this.consumerSupport());
return filter;
}
private OAuthConsumerProcessingFilter oauthConsumerProcessingFilter() {
OAuthConsumerProcessingFilter filter = new OAuthConsumerProcessingFilter();
filter.setProtectedResourceDetailsService(this.prds());
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map = new LinkedHashMap<>();
// one entry per oauth:url element in xml
map.put(
new AntPathRequestMatcher("/public/v1/**", null),
Collections.singletonList(new SecurityConfig(ID)));
filter.setObjectDefinitionSource(new DefaultFilterInvocationSecurityMetadataSource(map));
return filter;
}
#Bean
OAuthConsumerSupport consumerSupport() {
CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();
consumerSupport.setProtectedResourceDetailsService(prds());
return consumerSupport;
}
#Bean
ProtectedResourceDetailsService prds() {
InMemoryProtectedResourceDetailsService service = new InMemoryProtectedResourceDetailsService();
Map<String, ProtectedResourceDetails> store = new HashMap<>();
store.put(ID, prd());
service.setResourceDetailsStore(store);
return service;
}
ProtectedResourceDetails prd() {
ConsumerTokenDto consumerToken = getConsumerToken();
BaseProtectedResourceDetails resourceDetails = new BaseProtectedResourceDetails();
resourceDetails.setId(ID);
resourceDetails.setConsumerKey(consumerToken.getKey());
resourceDetails.setSharedSecret(new SharedConsumerSecretImpl(consumerToken.getSecret()));
resourceDetails.setRequestTokenURL("https://.../request_token");
// the authorization URL does not prompt for confirmation but immediately returns an OAuth verifier
resourceDetails.setUserAuthorizationURL(
"https://.../authorize?email=mail&password=pw");
resourceDetails.setAccessTokenURL("https://.../access_token");
resourceDetails.setSignatureMethod(HMAC_SHA1SignatureMethod.SIGNATURE_NAME);
return resourceDetails;
}
// get consumer token from provider
private ConsumerTokenDto getConsumerToken() {
if (consumerTokenDto == null) {
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("client", "Client");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
RestTemplate restTemplate = restTemplateBuilder.setConnectTimeout(1000).setReadTimeout(1000).build();
restTemplate.getInterceptors().add(interceptor);
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
ResponseEntity<ConsumerTokenDto> response = restTemplate
.exchange("https://.../consumer_token", HttpMethod.POST, request,
ConsumerTokenDto.class);
consumerTokenDto = response.getBody();
}
return consumerTokenDto;
}
// create oauth rest template
#Bean
public OAuthRestTemplate oAuthRestTemplate() {
OAuthRestTemplate oAuthRestTemplate = new OAuthRestTemplate(prd());
oAuthRestTemplate.getInterceptors().add(interceptor);
return oAuthRestTemplate;
}
}
I think I've found a solution. The trick is to implement my own OAuthConsumerContextFilter and replace the redirect call with a direct call to the authorization endpoint. I've commented the interesting parts below (starting with //!!!!).
CustomOAuthConsumerContextFilter
public class CustomOAuthConsumerContextFilter extends OAuthConsumerContextFilter {
private static final Logger LOG = LoggerFactory.getLogger(CustomOAuthConsumerContextFilter.class);
private RestTemplateBuilder restTemplateBuilder;
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
context.setDetails(request);
Map<String, OAuthConsumerToken> rememberedTokens =
getRememberMeServices().loadRememberedTokens(request, response);
Map<String, OAuthConsumerToken> accessTokens = new TreeMap<>();
Map<String, OAuthConsumerToken> requestTokens = new TreeMap<>();
if (rememberedTokens != null) {
for (Map.Entry<String, OAuthConsumerToken> tokenEntry : rememberedTokens.entrySet()) {
OAuthConsumerToken token = tokenEntry.getValue();
if (token != null) {
if (token.isAccessToken()) {
accessTokens.put(tokenEntry.getKey(), token);
} else {
requestTokens.put(tokenEntry.getKey(), token);
}
}
}
}
context.setAccessTokens(accessTokens);
OAuthSecurityContextHolder.setContext(context);
if (LOG.isDebugEnabled()) {
LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute() + "'.");
}
try {
try {
request.setAttribute(getAccessTokensRequestAttribute(), new ArrayList<>(accessTokens.values()));
chain.doFilter(request, response);
} catch (Exception e) {
try {
ProtectedResourceDetails resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e);
String neededResourceId = resourceThatNeedsAuthorization.getId();
//!!!! store reference to verifier here, outside of loop
String verifier = null;
while (!accessTokens.containsKey(neededResourceId)) {
OAuthConsumerToken token = requestTokens.remove(neededResourceId);
if (token == null) {
token = getTokenServices().getToken(neededResourceId);
}
// if the token is null OR
// if there is NO access token and (we're not using 1.0a or the verifier is not null)
if (token == null || (!token.isAccessToken() &&
(!resourceThatNeedsAuthorization.isUse10a() || verifier == null))) {
//no token associated with the resource, start the oauth flow.
//if there's a request token, but no verifier, we'll assume that a previous oauth request failed and we need to get a new request token.
if (LOG.isDebugEnabled()) {
LOG.debug("Obtaining request token for resource: " + neededResourceId);
}
//obtain authorization.
String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
token = getConsumerSupport().getUnauthorizedRequestToken(neededResourceId, callbackURL);
if (LOG.isDebugEnabled()) {
LOG.debug("Request token obtained for resource " + neededResourceId + ": " + token);
}
//okay, we've got a request token, now we need to authorize it.
requestTokens.put(neededResourceId, token);
getTokenServices().storeToken(neededResourceId, token);
String redirect =
getUserAuthorizationRedirectURL(resourceThatNeedsAuthorization, token, callbackURL);
if (LOG.isDebugEnabled()) {
LOG.debug("Redirecting request to " + redirect +
" for user authorization of the request token for resource " +
neededResourceId + ".");
}
request.setAttribute(
"org.springframework.security.oauth.consumer.AccessTokenRequiredException", e);
// this.redirectStrategy.sendRedirect(request, response, redirect);
//!!!! get the verifier from the authorization URL
verifier = this.getVerifier(redirect);
//!!!! start next iteration of loop -> now we have the verifier, so the else statement below shoud get executed and an access token retrieved
continue;
} else if (!token.isAccessToken()) {
//we have a presumably authorized request token, let's try to get an access token with it.
if (LOG.isDebugEnabled()) {
LOG.debug("Obtaining access token for resource: " + neededResourceId);
}
//authorize the request token and store it.
try {
token = getConsumerSupport().getAccessToken(token, verifier);
} finally {
getTokenServices().removeToken(neededResourceId);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Access token " + token + " obtained for resource " + neededResourceId +
". Now storing and using.");
}
getTokenServices().storeToken(neededResourceId, token);
}
accessTokens.put(neededResourceId, token);
try {
//try again
if (!response.isCommitted()) {
request.setAttribute(getAccessTokensRequestAttribute(),
new ArrayList<>(accessTokens.values()));
chain.doFilter(request, response);
} else {
//dang. what do we do now?
throw new IllegalStateException(
"Unable to reprocess filter chain with needed OAuth2 resources because the response is already committed.");
}
} catch (Exception e1) {
resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e1);
neededResourceId = resourceThatNeedsAuthorization.getId();
}
}
} catch (OAuthRequestFailedException eo) {
fail(request, response, eo);
} catch (Exception ex) {
Throwable[] causeChain = getThrowableAnalyzer().determineCauseChain(ex);
OAuthRequestFailedException rfe = (OAuthRequestFailedException) getThrowableAnalyzer()
.getFirstThrowableOfType(OAuthRequestFailedException.class, causeChain);
if (rfe != null) {
fail(request, response, rfe);
} else {
// Rethrow ServletExceptions and RuntimeExceptions as-is
if (ex instanceof ServletException) {
throw (ServletException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
// Wrap other Exceptions. These are not expected to happen
throw new RuntimeException(ex);
}
}
}
} finally {
OAuthSecurityContextHolder.setContext(null);
HashMap<String, OAuthConsumerToken> tokensToRemember = new HashMap<>();
tokensToRemember.putAll(requestTokens);
tokensToRemember.putAll(accessTokens);
getRememberMeServices().rememberTokens(tokensToRemember, request, response);
}
}
private String getVerifier(String authorizationURL) {
HttpEntity request = HttpEntity.EMPTY;
RestTemplate restTemplate = restTemplateBuilder.setConnectTimeout(1000).setReadTimeout(1000).build();
ResponseEntity<String> response =
restTemplate.exchange(authorizationURL, HttpMethod.GET, request, String.class);
//!!!! extract verifier from response
String verifier = response.getBody().split("=")[1];
return verifier;
}
void setRestTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
this.restTemplateBuilder = restTemplateBuilder;
}
}
The methods of RestTemplate such as postForEntity() throw RestClientException. I would like to extract the HTTP status code and response body from that exception object in the catch block. How can I do that?
Instead of catching RestClientException, catch the special HttpClientErrorException.
Here's an example:
try {
Link dataCenterLink = serviceInstance.getLink("dataCenter");
String dataCenterUrl = dataCenterLink.getHref();
DataCenterResource dataCenter =
restTemplate.getForObject(dataCenterUrl, DataCenterResource.class);
serviceInstance.setDataCenter(dataCenter);
} catch (HttpClientErrorException e) {
HttpStatus status = e.getStatusCode();
if (status != HttpStatus.NOT_FOUND) { throw e; }
}
HttpClientErrorException provides getStatusCode and getResponseBodyAsByteArray to get the status code and body, respectively.
Catch RestClientResponseException instead. It's more generic.
From the docs: Common base class for exceptions that contain actual HTTP response data.
In some cases, HttpClientErrorException is not thrown. For example the following method restTemplate.exchange call:
ResponseEntity<Employee[]> employees = restTemplate.exchange(url, HttpMethod.GET, entity, Employee[].class);
Gets the http body and marshalls it to an Entity. If remote resource returns a rare error, internal marshall does not work and just a RestClientException is thrown.
restTemplate.setErrorHandler
In this case or if you want to handle any error in restTemplate operations, you could use setErrorHandler. This method receives a basic ResponseErrorHandler with helpful methods.
This method hasError allowed me to get the remote http body text and helped me to detect the error of the invocation or in the remote http remote resource:
restTemplate.setErrorHandler(new ResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse arg0) throws IOException {
System.out.println("StatusCode from remote http resource:"+arg0.getStatusCode());
System.out.println("RawStatusCode from remote http resource:"+arg0.getRawStatusCode());
System.out.println("StatusText from remote http resource:"+arg0.getStatusText());
String body = new BufferedReader(new InputStreamReader(arg0.getBody()))
.lines().collect(Collectors.joining("\n"));
System.out.println("Error body from remote http resource:"+body);
return false;
}
#Override
public void handleError(ClientHttpResponse arg0) throws IOException {
// do something
}
});
Also, you can manually evaluate the body or status and return true or false in order to flag as error or not.
private void sendActivity(StatsActivity statsActivity) throws InterruptedException
{
LibraryConnectorXapiEditView libraryConnectorXapiEditView = (LibraryConnectorXapiEditView) workerBundle.getConnector();
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Statement statement = libraryConnectorConverter.convertActivityToStatement(statsActivity, workerBundle);
HttpEntity<Statement> request = new HttpEntity<>(statement, headers);
try
{
String lrsEndPoint = libraryConnectorXapiEditView.getLrsEndPoint() + "/statements";
ResponseEntity<String> response = restTemplate.exchange(lrsEndPoint, HttpMethod.POST, request, String.class);
ocnCompletionEventDao.save(this.convertToOcnCompletionEvent(statsActivity, response.getBody(), response.getStatusCodeValue()));
}
catch (HttpClientErrorException ex)
{
ocnCompletionEventDao.save(this.convertToOcnCompletionEvent(statsActivity, ex.getResponseBodyAsString(), ex.getStatusCode().value()));
checkResponse(ex, libraryConnectorXapiEditView);
if(failedAttempts<3)
{
sendActivity(statsActivity);
failedAttempts++;
}
}
}
private void checkResponse(HttpClientErrorException ex, LibraryConnectorXapiEditView libraryConnectorXapiEditView) throws InterruptedException
{
int statusCode = ex.getStatusCode().value();
int retryAfterSeconds = retryAfter(ex.getResponseHeaders());
switch (statusCode)
{
case 401:
headers = xApiAuthorizationUtils.getHeaders(libraryConnectorXapiEditView);
case 429:
if(retryAfterSeconds!=0)
Thread.sleep(retryAfterSeconds);
case 422:
failedAttempts=3;
}
}
The methods of RestTemplate such as postForEntity() throw RestClientException. I would like to extract the HTTP status code and response body from that exception object in the catch block. How can I do that?
Instead of catching RestClientException, catch the special HttpClientErrorException.
Here's an example:
try {
Link dataCenterLink = serviceInstance.getLink("dataCenter");
String dataCenterUrl = dataCenterLink.getHref();
DataCenterResource dataCenter =
restTemplate.getForObject(dataCenterUrl, DataCenterResource.class);
serviceInstance.setDataCenter(dataCenter);
} catch (HttpClientErrorException e) {
HttpStatus status = e.getStatusCode();
if (status != HttpStatus.NOT_FOUND) { throw e; }
}
HttpClientErrorException provides getStatusCode and getResponseBodyAsByteArray to get the status code and body, respectively.
Catch RestClientResponseException instead. It's more generic.
From the docs: Common base class for exceptions that contain actual HTTP response data.
In some cases, HttpClientErrorException is not thrown. For example the following method restTemplate.exchange call:
ResponseEntity<Employee[]> employees = restTemplate.exchange(url, HttpMethod.GET, entity, Employee[].class);
Gets the http body and marshalls it to an Entity. If remote resource returns a rare error, internal marshall does not work and just a RestClientException is thrown.
restTemplate.setErrorHandler
In this case or if you want to handle any error in restTemplate operations, you could use setErrorHandler. This method receives a basic ResponseErrorHandler with helpful methods.
This method hasError allowed me to get the remote http body text and helped me to detect the error of the invocation or in the remote http remote resource:
restTemplate.setErrorHandler(new ResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse arg0) throws IOException {
System.out.println("StatusCode from remote http resource:"+arg0.getStatusCode());
System.out.println("RawStatusCode from remote http resource:"+arg0.getRawStatusCode());
System.out.println("StatusText from remote http resource:"+arg0.getStatusText());
String body = new BufferedReader(new InputStreamReader(arg0.getBody()))
.lines().collect(Collectors.joining("\n"));
System.out.println("Error body from remote http resource:"+body);
return false;
}
#Override
public void handleError(ClientHttpResponse arg0) throws IOException {
// do something
}
});
Also, you can manually evaluate the body or status and return true or false in order to flag as error or not.
private void sendActivity(StatsActivity statsActivity) throws InterruptedException
{
LibraryConnectorXapiEditView libraryConnectorXapiEditView = (LibraryConnectorXapiEditView) workerBundle.getConnector();
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Statement statement = libraryConnectorConverter.convertActivityToStatement(statsActivity, workerBundle);
HttpEntity<Statement> request = new HttpEntity<>(statement, headers);
try
{
String lrsEndPoint = libraryConnectorXapiEditView.getLrsEndPoint() + "/statements";
ResponseEntity<String> response = restTemplate.exchange(lrsEndPoint, HttpMethod.POST, request, String.class);
ocnCompletionEventDao.save(this.convertToOcnCompletionEvent(statsActivity, response.getBody(), response.getStatusCodeValue()));
}
catch (HttpClientErrorException ex)
{
ocnCompletionEventDao.save(this.convertToOcnCompletionEvent(statsActivity, ex.getResponseBodyAsString(), ex.getStatusCode().value()));
checkResponse(ex, libraryConnectorXapiEditView);
if(failedAttempts<3)
{
sendActivity(statsActivity);
failedAttempts++;
}
}
}
private void checkResponse(HttpClientErrorException ex, LibraryConnectorXapiEditView libraryConnectorXapiEditView) throws InterruptedException
{
int statusCode = ex.getStatusCode().value();
int retryAfterSeconds = retryAfter(ex.getResponseHeaders());
switch (statusCode)
{
case 401:
headers = xApiAuthorizationUtils.getHeaders(libraryConnectorXapiEditView);
case 429:
if(retryAfterSeconds!=0)
Thread.sleep(retryAfterSeconds);
case 422:
failedAttempts=3;
}
}